HarmonyOS 鸿蒙Next readPixelsToBuffer

发布于 1周前 作者 sinazl 最后一次编辑是 5天前 来自 鸿蒙OS

HarmonyOS 鸿蒙Next readPixelsToBuffer

pixmap.readPixelsToBuffer(readBuffer).then(()=>{
this.savePicture(readBuffer)
}).catch((err:string)=>{
console.debug("出错了"+err)
})
一直报错无法正确转换成buffer

样例代码:


import componentSnapshot from '@ohos.arkui.componentSnapshot'
import image from '@ohos.multimedia.image'
import { promptAction } from '@kit.ArkUI'
import { BusinessError } from '@kit.BasicServicesKit';
import dataSharePredicates from '@ohos.data.dataSharePredicates';
import { abilityAccessCtrl, PermissionRequestResult,Permissions,bundleManager,common} from '@kit.AbilityKit';
import fs from '@ohos.file.fs';
// import { photoAccessHelper } from '@kit.MediaLibraryKit';
import PhotoAccessHelper from '@ohos.file.photoAccessHelper';
@Entry({ routeName: "SnapshotExample" })
@Component
export struct SnapshotExample {
  @State pixmap: image.PixelMap | undefined = undefined

  build() {
    Column() {
      Row() {
        Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5)
        Image($r('app.media.tips')).autoResize(true).width(200).height(200).margin(5).id("root")
      }
      Button("click to generate UI snapshot")
        .onClick(() => {
          componentSnapshot.get("root", (error: Error, pixmap: image.PixelMap) => {
            if (error) {
              console.log("error: " + JSON.stringify(error))
              return;
            }
            this.pixmap = pixmap
            const readBuffer: ArrayBuffer = new ArrayBuffer(160000); // 96为需要创建的像素buffer大小,取值为:height * width *4

            grantPermission().then((status:boolean)=>{
              if (status) {
                pixmap.readPixelsToBuffer(readBuffer).then(()=>{
                  this.savePicture(readBuffer)
                }).catch((err:string)=>{
                  console.debug("出错了"+err)
                })
              }
            })

            // let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
          })
        }).margin(10)
    }
    .width('100%')
    .height('100%')
    .alignItems(HorizontalAlign.Center)
  }

  async savePicture(buffer: ArrayBuffer): Promise<void> {
    let photoAccessHelper: PhotoAccessHelper.PhotoAccessHelper = PhotoAccessHelper.getPhotoAccessHelper(getContext(this) as common.UIAbilityContext);
    let options: PhotoAccessHelper.CreateOptions = {
      title: Date.now().toString()
    };
    let photoUri: string = await photoAccessHelper.createAsset(PhotoAccessHelper.PhotoType.IMAGE, 'jpg', options);
    console.info(photoUri)
    //createAsset的调用需要ohos.permission.READ_IMAGEVIDEO和ohos.permission.WRITE_IMAGEVIDEO的权限
    let file: fs.File = fs.openSync(photoUri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
    await fs.write(file.fd, buffer);
    fs.closeSync(file);
  }

}




const TAG: string = '[Permission]';

const PERMISSIONS: Array<Permissions> = [
  'ohos.permission.CAMERA',
  "ohos.permission.READ_IMAGEVIDEO",
  "ohos.permission.WRITE_IMAGEVIDEO"
];

const context = getContext(this) as common.UIAbilityContext;
export default async function grantPermission(): Promise<boolean> {
  try {
    let bundleInfo: bundleManager.BundleInfo =
      await bundleManager.getBundleInfoForSelf(
        bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION
      );
    let appInfo: bundleManager.ApplicationInfo = bundleInfo.appInfo;
    let tokenId = appInfo.accessTokenId;
    let atManager = abilityAccessCtrl.createAtManager();
    let pems: Array<Permissions> = [];
    for (let i = 0; i < PERMISSIONS.length; i++) {
      let state = await atManager.checkAccessToken(tokenId, PERMISSIONS[i]);
      if (state !== abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
        pems.push(PERMISSIONS[i]);
      }
    }
    if (pems.length > 0) {
      let ctx = context
      let result: PermissionRequestResult = await atManager.requestPermissionsFromUser(ctx, pems);
      let grantStatus: Array<number> = result.authResults;
      let length: number = grantStatus.length;
      for (let i = 0; i < length; i++) {
        if (grantStatus[i] !== 0) {
          return false;
        }
      }
    }
    return true;
  } catch (error) {
    return false;
  }
}

更多关于HarmonyOS 鸿蒙Next readPixelsToBuffer的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

可以参考如下代码:

import componentSnapshot from '[@ohos](/user/ohos).arkui.componentSnapshot'
import image from '[@ohos](/user/ohos).multimedia.image'
import { promptAction } from '[@kit](/user/kit).ArkUI'
import { BusinessError } from '[@kit](/user/kit).BasicServicesKit';
import dataSharePredicates from '[@ohos](/user/ohos).data.dataSharePredicates';
import { abilityAccessCtrl, PermissionRequestResult, Permissions, bundleManager, common } from '[@kit](/user/kit).AbilityKit';
import fs from '[@ohos](/user/ohos).file.fs';
// import { photoAccessHelper } from '[@kit](/user/kit).MediaLibraryKit';
import PhotoAccessHelper from '[@ohos](/user/ohos).file.photoAccessHelper';

[@Entry](/user/Entry)
[@Component](/user/Component)
export struct SnapshotExample {
 [@State](/user/State) pixmap: image.PixelMap | undefined = undefined

 build() {
   Column() {
     Row() {
       Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5)
       Image($r('app.media.ic_internet'))
         .autoResize(true)
         .width(200)
         .height(200)
         .margin(5)
         .id("root")
     }

     Button("click to generate UI snapshot")
       .onClick(() => {
         componentSnapshot.get("root", (error: Error, pixmap: image.PixelMap) => {
           if (error) {
             console.log("error: " + JSON.stringify(error))
             return;
           }
           this.pixmap = pixmap
           const readBuffer: ArrayBuffer = new ArrayBuffer(96); // 96为需要创建的像素buffer大小,取值为:height * width *4

           grantPermission().then((status: boolean) => {
             if (status) {

               let packOpts: image.PackingOption = { format: "image/jpeg", quality: 100 }
               const imagePacker = image.createImagePacker();
               imagePacker.packing(this.pixmap, packOpts)
                 .then(async (data: ArrayBuffer) => {
                   console.log('packing succeeded.');
                   this.savePicture(data)
                 }).catch((error: BusinessError) => {
                 console.log('packing failed.');
               })
               
             }
           })

      
         })
       }).margin(10)
   }
   .width('100%')
   .height('100%')
   .alignItems(HorizontalAlign.Center)
 }

 async savePicture(buffer: ArrayBuffer): Promise<void> {
   let photoAccessHelper: PhotoAccessHelper.PhotoAccessHelper =
     PhotoAccessHelper.getPhotoAccessHelper(getContext(this) as common.UIAbilityContext);
   let options: PhotoAccessHelper.CreateOptions = {
     title: Date.now().toString()
   };
   let photoUri: string = await photoAccessHelper.createAsset(PhotoAccessHelper.PhotoType.IMAGE, 'jpg', options);
   console.info(photoUri)
   //createAsset的调用需要ohos.permission.READ_IMAGEVIDEO和ohos.permission.WRITE_IMAGEVIDEO的权限
   let file: fs.File = fs.openSync(photoUri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
   await fs.write(file.fd, buffer);
   fs.closeSync(file);
 }
}


const TAG: string = '[Permission]';

const PERMISSIONS: Array<Permissions> = [
 'ohos.permission.CAMERA',
 "ohos.permission.READ_IMAGEVIDEO",
 "ohos.permission.WRITE_IMAGEVIDEO"
];

const context = getContext(this) as common.UIAbilityContext;

export default async function grantPermission(): Promise<boolean> {
 try {
   let bundleInfo: bundleManager.BundleInfo =
     await bundleManager.getBundleInfoForSelf(
       bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION
     );
   let appInfo: bundleManager.ApplicationInfo = bundleInfo.appInfo;
   let tokenId = appInfo.accessTokenId;
   let atManager = abilityAccessCtrl.createAtManager();
   let pems: Array<Permissions> = [];
   for (let i = 0; i < PERMISSIONS.length; i++) {
     let state = await atManager.checkAccessToken(tokenId, PERMISSIONS[i]);
     if (state !== abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
       pems.push(PERMISSIONS[i]);
     }
   }
   if (pems.length > 0) {
     let ctx = context
     let result: PermissionRequestResult = await atManager.requestPermissionsFromUser(ctx, pems);
     let grantStatus: Array<number> = result.authResults;
     let length: number = grantStatus.length;
     for (let i = 0; i < length; i++) {
       if (grantStatus[i] !== 0) {
         return false;
       }
     }
   }
   return true;
 } catch (error) {
   return false;
 }
}

更多关于HarmonyOS 鸿蒙Next readPixelsToBuffer的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙系统中,readPixelsToBuffer 方法通常用于从屏幕或某个视图(如Canvas)中读取像素数据到指定的缓冲区中。该方法一般属于图形处理或渲染类的一部分,常用于图像捕捉、处理或分析的场景。

具体实现上,readPixelsToBuffer 可能需要以下几个关键参数:

  1. 目标缓冲区:一个足够大的内存缓冲区,用于存储从屏幕或视图读取的像素数据。
  2. 像素格式:指定读取像素的格式,例如RGBA8888、RGB565等。
  3. 区域:指定要读取的像素区域,通常包括起始位置和宽高。
  4. 步长:缓冲区中每行像素数据的字节数,这可能与图像的宽度和像素格式有关。

示例调用可能如下(伪代码):

PixelBuffer buffer; // 预先分配好足够大小的缓冲区
PixelFormat format = PixelFormat::RGBA8888;
Rect area = Rect(0, 0, width, height);
int stride = width * 4; // 假设RGBA8888格式,每像素4字节

readPixelsToBuffer(buffer, format, area, stride);

如果readPixelsToBuffer方法在你的具体开发环境中表现异常或不被识别,请检查你的开发环境是否支持该方法,以及是否包含了必要的头文件或库。如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html。

回到顶部