鸿蒙开发中 将image.PixelMap类型图片 保存到手机相册
·
import { componentSnapshot, promptAction } from '@kit.ArkUI'
import { image } from '@kit.ImageKit'
import { fileIo, fileUri } from '@kit.CoreFileKit'
import { photoAccessHelper } from '@kit.MediaLibraryKit'
@Entry
@Component
struct Test {
@State img: image.PixelMap | null = null
build() {
Column() {
// 1.生成二维码
QRCode('czy_handsome')
.id('qrCode').width(100).aspectRatio(1)
SaveButton()
.onClick(async () => {
// 2.通过component,获取组件的像素类型
this.img = componentSnapshot.getSync('qrCode')
// 3.将像素点转换成为 buffer流
const packer = image.createImagePacker()
const buffer = await packer.packing(this.img, {
format: 'image/jpeg',
quality: 100
})
// 4.将buffer存入缓存目录中
// 4.1获取目标路径
const endPath = `${getContext(this).cacheDir}/${Date.now()}.jpg`
// 4.2给创建和读写的权限
const file = fileIo.openSync(endPath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE)
// 4.3将buffer写入
fileIo.writeSync(file.fd, buffer)
fileIo.closeSync(file.fd)
// 5.将缓存目录中的资源 存入图片中
// 5.1获取实例对象
const helper = photoAccessHelper.getPhotoAccessHelper(getContext(this))
// 5.2获取uri
const uri = fileUri.getUriFromPath(endPath)
// 5.3获取请求
const req = photoAccessHelper.MediaAssetChangeRequest.createImageAssetRequest(getContext(this), uri)
// 5.4保存到相册
await helper.applyChanges(req)
promptAction.showToast({ message: '图片保存成功' })
})
Image(this.img).width(100).aspectRatio(1)
}
}
}
更多推荐


所有评论(0)