HarmonyOS鸿蒙Next中APP开发怎么通过一个网络图片的URL地址获取其原始宽高信息?
HarmonyOS鸿蒙Next中APP开发,在不使用Image组件的情况下,怎么通过一个网络图片的URL地址获取其原始宽高信息?
【解决方案】
获取网络图片的宽高,可以将网络图片下载下来,然后将网络图片转换成PixelMap再通过getImageInfo方法获取图片的宽高。
httpRequest() {
  http.createHttp()
    .request(this.url,
      {
        expectDataType: http.HttpDataType.ARRAY_BUFFER, // 可选,指定返回数据的类型
      },
      (error: BusinessError, data: http.HttpResponse) => {
        if (error) {
          console.error(`http reqeust failed with. Code: ${error.code}, message: ${error.message}`);
        } else {
          console.log('http reqeust success.');
          let imageData: ArrayBuffer = data.result as ArrayBuffer;
          let imageSource: image.ImageSource = image.createImageSource(imageData);
          console.log(`http reqeust size = ${imageData.byteLength}`);
          let options: Record<string, number | boolean> = {
            'alphaType': 0, // 透明度
            'editable': false, // 是否可编辑
            'pixelFormat': 3, // 像素格式
            'scaleMode': 1, // 缩略值
          } // 创建图片大小
          imageSource.createPixelMap(options).then((pixelMap: PixelMap) => {
            this.imagePixelMap = pixelMap
            this.imagePixelMap?.getImageInfo().then((imageInfo: image.ImageInfo) => {
              if (imageInfo == undefined) {
                console.error("Failed to obtain the image pixel map information.");
              }
              let witht = imageInfo.size.width;
              let hig = imageInfo.size.height;
              console.log("Succeeded in obtaining the image pixel map information.", witht, hig);
            })
          })
        }
      })
}
【背景知识】
createImageSource通过传入的uri创建ImageSource实例。
createPixelMap通过属性创建PixelMap。
getImageInfo获取图像像素信息。
更多关于HarmonyOS鸿蒙Next中APP开发怎么通过一个网络图片的URL地址获取其原始宽高信息?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
先下载到本地沙盒
import http from '@kit.NetworkKit';
async function downloadImage(url: string): Promise<string> {
  const httpRequest = http.createHttp();
  const response = await httpRequest.request(url, { method: http.RequestMethod.GET });
  return await saveToTempFile(response.result); // 自定义保存到沙箱路径
}
然后解析图片元数据
import image from '@kit.ImageKit';
async function getImageSize(filePath: string): 
  Promise<{ width: number, height: number }> {
  const options: image.InitializationOptions = {
    inJustDecodeBounds: true // 关键参数:仅解码尺寸不加载像素
  };
  const imageSource = image.createImageSource(filePath);
  const size = await imageSource.getImageInfo();
  return { width: size.size.width, height: size.size.height };
}
import { image } from '@kit.ImageKit';
在鸿蒙(HarmonyOS)APP 开发中,若不使用 Image 组件,可通过 “下载图片二进制数据→解析图片元数据” 的方式获取网络图片的原始宽高。核心思路是利用鸿蒙的网络请求 API 下载图片数据,再通过图片处理 API 解析其宽高信息,无需渲染图片。
如果是自有服务,可以针对图片,增加获取宽高信息的接口,传入图片信息,返回宽高信息
可以通过http, createImageSource;createPixelMap;getImageInfo这四个API来实现,具体可以看一下我代码:先用http下载,然后保存到沙箱目录,之后在获取沙箱文件访问图片信息
let httpRequest = http.createHttp()
let data = await httpRequest.request(url);
if (data?.responseCode == http.ResponseCode.OK) {
            let imgFile = fileIo.openSync('你要存的沙箱地址', fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
            await fileIo.write(imgFile.fd, data.result as ArrayBuffer);
            const uriFile = fileIo.openSync('‘你要存的沙箱地址’', fileIo.OpenMode.READ_ONLY);
const imageSource = image.createImageSource(uriFile.fd);
const imageInfo = await imageSource.getImageInfo();
imageSizes.push({
  width: imageInfo.size.width,
  height: imageInfo.size.height
});
}
只能下载后看pixelmap宽高了,
在HarmonyOS Next中,使用网络图片URL获取原始宽高信息,可通过Image组件结合onLoad回调实现。加载图片时,onLoad事件会返回图片的原始尺寸数据,包括width和height属性。示例代码:Image(src: url).onLoad((event: { width: number, height: number }) => { /* 获取宽高 */ })。此方法直接获取图片元数据,无需额外解析或依赖外部库。
在HarmonyOS Next中,可通过以下方式获取网络图片的原始宽高信息:
- 使用HttpURLConnection或HttpClient请求图片URL,获取响应头中的Content-Type和Content-Length信息
- 通过ImageSource类解析图片数据:
// 获取图片输入流
InputStream inputStream = connection.getInputStream();
ImageSource.SourceOptions options = new ImageSource.SourceOptions();
options.formatHint = "image/jpeg"; // 根据实际格式设置
ImageSource imageSource = ImageSource.create(inputStream, options);
ImageInfo imageInfo = imageSource.getImageInfo();
int width = imageInfo.size.width;
int height = imageInfo.size.height;
- 或者使用ImageDecoder:
ImageDecoder.Source source = ImageDecoder.createSource(byteArray); // 从字节数据创建
ImageDecoder decoder = ImageDecoder.createDecoder(source);
int width = decoder.getWidth();
int height = decoder.getHeight();
注意事项:
- 需要处理网络请求权限和异常
- 建议在异步线程中执行,避免阻塞UI
- 大图片建议只读取元数据,不要完整加载到内存
这种方法无需实际渲染图片即可获取原始尺寸信息。
 
        
       
                   
                   
                  

