效果展示
实现思路

完整代码
typescript
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { fileIo } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';
import { promptAction } from '@kit.ArkUI';
import { BusinessError, request } from '@kit.BasicServicesKit';
import { image } from '@kit.ImageKit';
async function savePhotoToGallery(context: common.UIAbilityContext, url:string) {
let helper = photoAccessHelper.getPhotoAccessHelper(context);
try {
// onClick触发后10秒内通过createAsset接口创建图片文件,10秒后createAsset权限收回。
let uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpg');
// 使用uri打开文件,可以持续写入内容,写入过程不受时间限制
let file = await fileIo.open(uri, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
// 写到媒体库文件中
const source = image.createImageSource(url) // 图片对象
const packer = image.createImagePacker() // 创建打包对象
const buffer = await packer.packing(source, {
quality: 100,
format: 'image/jpeg'
})
await fileIo.write(file.fd, buffer);
await fileIo.close(file.fd);
promptAction.showToast({ message: '已保存至相册!' });
}
catch (error) {
const err: BusinessError = error as BusinessError;
console.error(`Failed to save photo. Code is ${err.code}, message is ${err.message}`);
}
}
@Entry
@Component
struct Index {
build() {
Row() {
Column({ space: 10 }) {
// $r('app.media.startIcon')需要替换为开发者所需的图像资源文件
Image('http://tmp00002.zhaodashen.cn/jd.png').width('100%')
SaveButton()
.padding({top: 12, bottom: 12, left: 24, right: 24})
.onClick(async (event: ClickEvent, result: SaveButtonOnClickResult) => {
if (result === SaveButtonOnClickResult.SUCCESS) {
const context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
// 免去权限申请和权限请求等环节,获得临时授权,保存对应图片
// =======================
try {
// 需要手动将 url 替换为真实服务器的 HTTP 协议地址
request.downloadFile(
getContext(),
{
url: 'http://tmp00002.zhaodashen.cn/jd.png',
filePath: context.filesDir + '/hello3.jpg'
}
).then((data: request.DownloadTask) => {
let downloadTask: request.DownloadTask = data;
downloadTask.on('progress', (receivedSize: number, totalSize: number) => {
console.log('下载中:', receivedSize, totalSize)
})
downloadTask.on('complete', () => {
console.log('下载完成') // 保存到媒体库中✅
savePhotoToGallery(context, context.filesDir + '/hello3.jpg');
})
}).catch((err: BusinessError) => {
console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`);
})
} catch (err) {
console.error(`Failed to request the download. err: ${JSON.stringify(err)}`);
}
// =======================
} else {
promptAction.showToast({ message: '设置权限失败!' })
}
})
}
.width('100%')
}
.height('100%')
.backgroundColor(0xF1F3F5)
}
}
