HarmonyOS鸿蒙Next中如何获取media目录下某张图片的宽高信息

HarmonyOS鸿蒙Next中如何获取media目录下某张图片的宽高信息 在不使用Image组件的情况下,如何获取本地资源目录下图片的宽高信息?

4 回复

可以参考以下demo:

import photoAccessHelper from '@ohos.file.photoAccessHelper';
import { image } from '@kit.ImageKit';
import { common, Permissions } from '@kit.AbilityKit';
import { fileIo as fs } from '@kit.CoreFileKit';

const permissions: Permissions[] = ['ohos.permission.READ_IMAGEVIDEO'];

@Entry
@Component
struct PhotoSizeDemo {
  @State imageWidth: number = 0;
  @State imageHeight: number = 0;
  @State selectedImageUri: string = '';
  context: Context = this.getUIContext().getHostContext() as common.UIAbilityContext;

  // 选择图片并获取宽高
  private async selectPhoto(): Promise<void> {
    try {
      let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
      photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
      photoSelectOptions.maxSelectNumber = 1;
      let photoPicker = new photoAccessHelper.PhotoViewPicker();
      const result: photoAccessHelper.PhotoSelectResult = await photoPicker.select(photoSelectOptions);
      // 文件选择成功后,返回PhotoSelectResult结果集
      console.log('选择成功,返回结果: ' + JSON.stringify(result));
      console.log('选择的文件数量: ' + result.photoUris.length);

      this.selectedImageUri = result.photoUris[0];

      // 打开文件描述符
      const file = fs.openSync(this.selectedImageUri, fs.OpenMode.READ_ONLY);

      // 创建缓冲区
      const fileSize = fs.statSync(file.fd).size;
      const buffer = new ArrayBuffer(fileSize);

      // 读取数据流
      fs.readSync(file.fd, buffer); // buffer即为文件流
      fs.closeSync(file); // 关闭文件

      // 3. 创建ImageSource实例
      const imageSource: image.ImageSource = image.createImageSource(buffer);

      // 4. 同步获取图片信息
      const imageInfo = imageSource.getImageInfoSync();
      if (imageInfo) {
        this.imageWidth = imageInfo.size.width;
        this.imageHeight = imageInfo.size.height;
      }
    } catch (err) {
      console.error(`Photo selection failed: ${JSON.stringify(err)}`);
    }
  }

  build() {
    Column({ space: 20 }) {
      Button('选择照片')
        .width(200)
        .height(50)
        .onClick(async () => {
          this.selectPhoto();
        });

      if (this.selectedImageUri) {
        Image(this.selectedImageUri)
          .width(300)
          .height(300)
          .margin(10);
      }

      Text(`宽度: ${this.imageWidth}px`)
        .fontSize(20);
      Text(`高度: ${this.imageHeight}px`)
        .fontSize(20);
    }
    .width('100%')
    .height('100%')
    .padding(20);
  };
}

更多关于HarmonyOS鸿蒙Next中如何获取media目录下某张图片的宽高信息的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS Next中,使用@ohos.file.fs@ohos.multimedia.image模块获取图片宽高。首先通过fs.openSync打开文件,获取FD。然后使用image.createImageSource(fd)创建ImageSource对象,调用其getImageInfo()方法即可获取包含width和height的图片信息。最后需关闭FD。

在HarmonyOS Next中,若不使用Image组件,可以通过ImageSourceResourceManager来获取本地媒体资源的宽高信息。以下是核心步骤:

  1. 获取ResourceManager实例:通过context.resourceManager访问资源管理器。
  2. 读取图片资源:使用ResourceManager.getMediaContent方法获取图片的ArrayBuffer数据。
  3. 创建ImageSource对象:将ArrayBuffer传入image.createImageSource方法创建ImageSource实例。
  4. 解码并获取属性:调用ImageSource.createPixelMap方法(可指定解码参数)获取PixelMap对象,从中读取widthheight属性。

关键代码示例(以获取media/example.jpg为例):

import image from '@ohos.multimedia.image';
import resourceManager from '@ohos.resourceManager';

// 1. 获取ResourceManager
const resMgr = context.resourceManager;

// 2. 读取图片资源
let mediaData: ArrayBuffer = await resMgr.getMediaContent($r('app.media.example').id);

// 3. 创建ImageSource
let imageSource: image.ImageSource = image.createImageSource(mediaData);

// 4. 解码并获取宽高
let pixelMap: image.PixelMap = await imageSource.createPixelMap();
let width: number = pixelMap.width;
let height: number = pixelMap.height;

// 使用后释放资源
pixelMap.release();
imageSource.release();

注意事项

  • 确保资源路径正确,$r('app.media.example')对应resources/base/media/目录下的example.jpg文件。
  • 操作涉及异步调用,需在异步函数中使用await或处理Promise。
  • 获取宽高后及时调用release()释放资源,避免内存泄漏。
  • 此方法适用于未压缩的位图资源,若需调整解码参数(如尺寸),可在createPixelMap中配置InitializationOptions

该方法直接操作原始图像数据,适用于需要获取元信息而不渲染的场景,如资源预处理或布局计算。

回到顶部