鸿蒙保存图片到相册
1.base64图片数据保存到相册
const base64Data: string = data as string const base64Str = base64Data.split(',')[1]; const imgBuffer = buffer.from(base64Str, 'base64') bufferArray = imgBuffer.buffer
const context = getContext();let helper = photoAccessHelper.getPhotoAccessHelper(context);let uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'png', {title: fileName,})let file = await fileIo.open(uri, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);// 写入图片fileIo.writeSync(file.fd, bufferArray);// 关闭文件await fileIo.close(file.fd);sysToast($r('app.string.toast_saved'))
2.base64图片数据转PixelMap
const base64Data: string = data as string const base64Str = base64Data.split(',')[1]; const imgBuffer = buffer.from(base64Str, 'base64')
bufferArray = imgBuffer.buffer
// 创建ImageSource const imageSource = image.createImageSource(bufferArray);const decodingOptions : image.DecodingOptions = {desiredSize: { width: 0, height: 0 }, // 0表示使用原始尺寸desiredPixelFormat: image.PixelMapFormat.RGBA_8888,desiredRegion: { size: { width: 0, height: 0 }, x: 0, y: 0 } }; const pixelMap = await imageSource.createPixelMap(decodingOptions);saveTo(pixelMap)
3.PixelMap转ArrayBuffer
const imagePackerApi = image.createImagePacker(); const packOpts: image.PackingOption = {format: 'image/jpeg', // 'image/jpeg' 或 'image/png'quality: 100 // 质量,对JPEG有效 (0-100) };try {bufferArray = await imagePackerApi.packing(data, packOpts); } catch (packError) {console.error(`Failed to pack image. Code: ${(packError as BusinessError).code}, message: ${(packError as BusinessError).message}`); }
4. 从共享视频组件获取当前帧图像
const id = this.xComponentController.getXComponentSurfaceId(); const backgroundPix: PixelMap = await image.createPixelMapFromSurface(id);
5.叠加组合2个PixelMap
if (!foregroundPix || !backgroundPix) {return undefined; }// 使用背景图片的尺寸作为目标尺寸 const imageInfo = await backgroundPix.getImageInfo() const width = imageInfo.size.width; const height = imageInfo.size.height;const canvas = new drawing.Canvas(backgroundPix);let rect: common2D.Rect = { left: 0, top: 0, right: width, bottom: height } // 依次绘制每张图片 canvas.drawImageRect(foregroundPix, rect);return backgroundPix;