HarmonyOS readPixelsToBuffer

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

一直报错无法正确转换成buffer

HarmonyOS readPixelsToBuffer  -鸿蒙开发者社区

HarmonyOS
2024-12-27 15:45:33
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
FengTianYa
//方案一:
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
@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.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 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;
  }
}

//方案二:
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.startIcon')).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

            //修改点
            let pixelBytesNumber: number = this.pixmap.getPixelBytesNumber();
            const readBuffer: ArrayBuffer = new ArrayBuffer(pixelBytesNumber); // 96为需要创建的像素buffer大小,取值为:height * width *4

            grantPermission().then((status:boolean)=>{
              if (status) {
                pixmap.readPixelsToBuffer(readBuffer, (err: BusinessError, res: void) => {
                  if(err) {
                    // console.error('Failed to read image pixel data.'); //不符合条件则进入
                    console.debug("出错了"+err)
                    return;
                  } else {
                    // console.info('Succeeded in reading image pixel data.'); //符合条件则进入
                    this.savePicture(readBuffer)
                  }
                })
              }
            })

          })
        }).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("保存的图片uri为:"+photoUri)

    let file = await fs.open(photoUri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
    context.resourceManager.getMediaContent($r('app.media.icon123').id, 0)
      .then(async value => {
        let media = value.buffer;
        // 写到媒体库文件中
        await fs.write(file.fd, media);
        await fs.close(file.fd);
        promptAction.showToast({ message: '已保存至相册!' });
      });
  }
}
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;
  }
}
分享
微博
QQ
微信
回复
2024-12-27 18:52:37
相关问题
HarmonyOS jsbridge HarmonyOS版本
190浏览 • 1回复 待解决
HarmonyOS关于异步Promise的使用问题
644浏览 • 1回复 待解决
HarmonyOS HarmonyOS社区组件问题
435浏览 • 1回复 待解决
HarmonyOS JsBridge的HarmonyOS版本sdk
256浏览 • 1回复 待解决
HarmonyOS HarmonyOS签名验签问题
139浏览 • 1回复 待解决
HarmonyOS
110浏览 • 1回复 待解决
HarmonyOS 关于HarmonyOS应用的备案
103浏览 • 1回复 待解决
HarmonyOS flutter接入HarmonyOS原生视图
173浏览 • 1回复 待解决
HarmonyOS react-native-screens HarmonyOS计划
146浏览 • 1回复 待解决
HarmonyOS TabContent
541浏览 • 1回复 待解决
HarmonyOS responseRegion
298浏览 • 1回复 待解决
HarmonyOS Websocket?
214浏览 • 0回复 待解决
HarmonyOS DatePicker
139浏览 • 1回复 待解决
HarmonyOS gesture
74浏览 • 1回复 待解决
HarmonyOS NodeRender
74浏览 • 1回复 待解决
HarmonyOS bouncycastle
69浏览 • 1回复 待解决
HarmonyOS 可以用仓颉开发HarmonyOS
136浏览 • 1回复 待解决