鸿蒙下载图片保存到相册,截取某个组件保存到相册
import { image } from '@kit.ImageKit'
import photoAccessHelper from '@ohos.file.photoAccessHelper'
import { BusinessError } from '@kit.BasicServicesKit'
import { http } from '@kit.NetworkKit'
import fs from '@ohos.file.fs';
import { fileUri } from '@kit.CoreFileKit';
import { Context, Permissions } from '@kit.AbilityKit';
import { componentSnapshot } from '@kit.ArkUI';
import { PermissionUtil } from '../util/PermissionUtil';
import { PhotoHelper } from '../util/PhotoHelper';
import { FileUtil } from '../util/FileUtil';
import { LogUtil } from '@ohos/commonlibrary';
//保存画报到相册
function savePictorialToPhoto() {
//TODO:
let pixmap: image.PixelMap | undefined = undefined
let uriStr: string = ''
//截图,“root”是组件的id
let pixelmap = componentSnapshot.getSync("root", { scale: 2, waitUntilRenderFinished: true })
pixmap = pixelmap
console.log("测试保存"+JSON.stringify(pixmap))
//保存本地-相册
//Dialog截图
let ps: Permissions[] = ['ohos.permission.WRITE_IMAGEVIDEO'];
PermissionUtil.requestPermissions(ps).then((result) => {
if (result) {
LogUtil.debug("测试保存"+result)
let imgName = `海报_${new Date().getTime()}`;
PhotoHelper.save(photoAccessHelper.PhotoType.IMAGE, 'png', { title: imgName }).then(async (uri) => {
if (uri) {
uriStr = `调用2保存图片,返回uris:\n${uri}`
let file = FileUtil.openSync(uri);
let packOpts: image.PackingOption = { format: 'image/png', quality: 100 }
PhotoHelper.packToFileFromPixelMap(pixmap!!, file.fd, packOpts).then(() => {
FileUtil.close(file.fd);
console.log("测试保存成功")
})
}
}).catch((err: BusinessError) => {
uriStr = `调用保存图片,异常:\n${JSON.stringify(err)}`
})
} else {
console.log("测试保存失败")
}
})
}
@Entry
@Component
/**
*首页
*/
struct CeshiPage {
build() {
//底部导航栏
Column() {
Button('测试保存相册').onClick(() => {
this.dowImageAndSave("http://img14.360buyimg.com/imgzone/jfs/t1/317716/18/12967/150513/686749d5Fef9f99f1/eeefe1ff7bce6117.png",
getContext())
})
Button('测试截图保存相册').onClick(() => {
savePictorialToPhoto()
})
}
.id("root")
.width('100%').height('100%')
}
async dowImageAndSave(url: string, context: Context) {
let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context)
let pixelMap: PixelMap | undefined = undefined
let packOptions: image.PackingOption = { format: 'image/jpeg', quality: 98 }
let imagePackerApi = image.createImagePacker()
// 下载图片到本地
http.createHttp().request(url, {
method: http.RequestMethod.GET,
connectTimeout: 60000,
readTimeout: 60000
}, async (error: BusinessError, data: http.HttpResponse) => {
if (error) {
console.log(`${error.code},${error.message}`)
} else {
let imageData: ArrayBuffer = data.result as ArrayBuffer
let ImageSource: image.ImageSource = image.createImageSource(imageData)
// 创建pixelmap对象
pixelMap = await ImageSource.createPixelMap()
const path: string = context.cacheDir + "/save_image.jpg"
// 写入本地
let file = fs.openSync(path, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE)
await imagePackerApi.packToFile(pixelMap, file.fd, packOptions)
// 获取图片uri
let uri = fileUri.getUriFromPath(path)
// 复制图片到相册
let uris: Array<string> = [uri]
let photoCreationConfig: Array<photoAccessHelper.PhotoCreationConfig> = [
{
title: 'dowImg',
fileNameExtension: 'jpg',
photoType: photoAccessHelper.PhotoType.IMAGE,
subtype: photoAccessHelper.PhotoSubtype.DEFAULT
}
]
// 基于弹窗授权的方式获取媒体库的目标uri
let desFileuris: Array<string> = await phAccessHelper.showAssetsCreationDialog(uris, photoCreationConfig)
// 将应用沙箱的照片写入媒体库
let desFile: fs.File = await fs.open(desFileuris[0], fs.OpenMode.WRITE_ONLY) // 相册
let srcFile: fs.File = await fs.open(uri, fs.OpenMode.READ_ONLY) // 沙箱图片
// 沙箱图片复制到相册
await fs.copyFile(srcFile.fd, desFile.fd).then(() => {
fs.close(srcFile)
fs.close(desFile)
})
}
})
//=====================
}
}