#鸿蒙通关秘籍#如何使用PixelMap深拷贝实现图片裁剪?

HarmonyOS
2024-12-03 10:32:15
6233浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
网络小先锋

在图片开发中,经常需要对PixelMap对象进行深拷贝,从而实现图片的裁剪。在项目中,通过以下步骤可以轻松实现:

  1. 使用readPixelsToBuffer方法将PixelMap读取到ArrayBuffer中。这一步确保拷贝后的数据是BGRA_8888格式。
  2. 使用createPixelMap方法将ArrayBuffer转换为目标PixelMap对象,并设置为RGBA_8888格式。
  3. 在应用启动时,通过管理资源,获取文件内容并转换为ImageSourcePixelMap
  4. 根据比例调整需要裁剪的高宽,调用crop方法进行裁剪。

完整的代码实现如下:

async function copyPixelMap(pm: PixelMap): Promise<PixelMap> {
  const imageInfo: image.ImageInfo = await pm.getImageInfo();
  const buffer: ArrayBuffer = new ArrayBuffer(pm.getPixelBytesNumber());
  await pm.readPixelsToBuffer(buffer);
  const opts: image.InitializationOptions = {
    editable: true,
    pixelFormat: image.PixelMapFormat.RGBA_8888,
    size: { height: imageInfo.size.height, width: imageInfo.size.width }
  };
  return await image.createPixelMap(buffer, opts);
}

async function aboutToAppear(): Promise<void> {
  const context: Context = getContext(this);
  const resourceMgr: resourceManager.ResourceManager = context.resourceManager;
  const fileData: Uint8Array = await resourceMgr.getRawFileContent(ImageCropConstants.RAWFILE_PICPATH);
  const buffer = fileData.buffer.slice(fileData.byteOffset, fileData.byteLength + fileData.byteOffset);
  this.imageSource = image.createImageSource(buffer);
  const decodingOptions: image.DecodingOptions = {
    editable: false,
    desiredPixelFormat: image.PixelMapFormat.BGRA_8888,
  }
  this.pixelMapSrc = await this.imageSource.createPixelMap(decodingOptions);
  this.pixelMapDst = await copyPixelMap(this.pixelMapSrc!);
}

async function cropImage(proportion: number): Promise<void> {
  const pixelMapTemp = await copyPixelMap(this.pixelMapSrc);
  const imageInfo: image.ImageInfo = await pixelMapTemp.getImageInfo();
  let imageHeight: number = imageInfo.size.height;
  let imageWith: number = imageInfo.size.width;
  if (proportion === ImageCropConstants.ONE_ONE) {
    if (imageHeight > imageWith) {
      imageHeight = imageWith;
    } else {
      imageWith = imageHeight;
    }
  }
  await pixelMapTemp.crop({ size: { height: imageHeight / proportion, width: imageWith }, x: 0, y: 0 });
  this.pixelMapDst = pixelMapTemp;
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.

分享
微博
QQ
微信
回复
2024-12-03 11:42:35


相关问题
HarmonyOS pixelmap拷贝问题
1602浏览 • 1回复 待解决
HarmonyOS image的pixelmap如何进行拷贝
706浏览 • 1回复 待解决
HarmonyOS 对象实现拷贝
1250浏览 • 1回复 待解决
HarmonyOS 浅拷贝拷贝
1361浏览 • 1回复 待解决
ArkTS中如何实现对象的拷贝
1879浏览 • 1回复 待解决
HarmonyOS 如何对数组进行拷贝
1272浏览 • 1回复 待解决
如何实现图片裁剪、旋转
1438浏览 • 1回复 待解决
HarmonyOS PixelMap裁剪
1021浏览 • 1回复 待解决
ArkWeb组件是否支持拷贝
1577浏览 • 1回复 待解决
HarmonyOS ArkWeb组件是否支持拷贝
1554浏览 • 2回复 待解决
想要实现一个图片裁剪的功能
1243浏览 • 1回复 待解决
HarmonyOS 如何进行图片裁剪
948浏览 • 1回复 待解决