中国优质的IT技术网站
专业IT技术创作平台
IT职业在线教育平台
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 @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; } }