HarmonyOS鸿蒙Next中保存column中的内容到相册
HarmonyOS鸿蒙Next中保存column中的内容到相册
column中包含图片,用户姓名,二维码等信息,想要将这些信息当成一个图片点击保存到相册中
参考demo
安全保存控件:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/photoaccesshelper-savebutton-V5
import componentSnapshot from '[@ohos](/user/ohos).arkui.componentSnapshot'
import image from '[@ohos](/user/ohos).multimedia.image'
import { photoAccessHelper } from '[@kit](/user/kit).MediaLibraryKit'
import fs from '[@ohos](/user/ohos).file.fs';
import { BusinessError } from '[@ohos](/user/ohos).base';
[@Entry](/user/Entry)
[@Component](/user/Component)
struct Index {
[@State](/user/State) pixmap: image.PixelMap | undefined = undefined
[@State](/user/State) saveButtonOptions: SaveButtonOptions = {
icon: SaveIconStyle.FULL_FILLED,
text: SaveDescription.SAVE_IMAGE,
buttonType: ButtonType.Capsule
} // 设置安全控件按钮属性
build() {
Column() {
Row() {
Text('截图测试')
Image($r('app.media.app_icon'))
.autoResize(true)
.width(200)
.height(200)
.margin(5)
}
.id("root")
Row() {
Image(this.pixmap).width('100%').height(200).border({ color: Color.Black, width: 2 }).margin(5)
}
SaveButton(this.saveButtonOptions)
.onClick(async (event, result: SaveButtonOnClickResult) => {
if (result == SaveButtonOnClickResult.SUCCESS) {
try {
// 需要确保fileUri对应的资源存在
componentSnapshot.get("root")
.then(pixmap: image.PixelMap) => {
this.pixmap = pixmap
//保存到相册
let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 };
const imagePackerApi = image.createImagePacker();
imagePackerApi.packing(pixmap, packOpts).then(async (buffer: ArrayBuffer) => {
try {
const context = getContext(this)
let helper = photoAccessHelper.getPhotoAccessHelper(context)
let uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'png')
let file = await fs.open(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
await fs.write(file.fd, buffer);
// 关闭文件
await fs.close(file.fd);
} catch (error) {
console.error("error is " + JSON.stringify(error))
}
}).catch((error: BusinessError) => {
console.error('Failed to pack the image. And the error is: ' + error);
})
}).catch((err: Error) => {
console.log("error: " + err)
})
} catch (err) {
console.error(`create asset failed with error: ${err.code}, ${err.message}`);
}
} else {
console.error('SaveButtonOnClickResult create asset failed');
}
})
}
.width('100%')
.height('100%')
.alignItems(HorizontalAlign.Center)
}
}
更多关于HarmonyOS鸿蒙Next中保存column中的内容到相册的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
可以使用componentSnapshot
将组件截图生成图片(pixelMap形式),
再用imagePacker
将图片转为ArrayBuffer
形式,
配合photoAccessHelper
、fs
获取路径、保存文件。
按钮上使用SaveButton
进行保存图片(无需额外申请权限)
以下为代码和效果:
import componentSnapshot from '@ohos.arkui.componentSnapshot'
import { image } from '@kit.ImageKit'
import photoAccessHelper from '@ohos.file.photoAccessHelper'
import fs from '@ohos.file.fs';
import { promptAction } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct Page2 {
build() {
Column() {
Column() {
Text('文字123')
Text('文字456')
SymbolGlyph($r('sys.symbol.save'))
}
.justifyContent(FlexAlign.Center)
.backgroundColor(0xdddddd)
.height('20%')
.width('100%')
.id('snapshot') // 绑定id
// 保存按钮 (鸿蒙安全控件的保存控件)文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-security-components-savebutton-V5#savebutton-1
SaveButton({ icon: SaveIconStyle.FULL_FILLED, text: SaveDescription.SAVE_IMAGE, buttonType: ButtonType.Normal })
.layoutDirection(SecurityComponentLayoutDirection.VERTICAL)
.backgroundColor(Color.White)
.iconSize(28)
.iconColor(0x818181)
.fontSize(12)
.fontColor(0x818181)
.borderRadius(12)
.width(70)
.height(70)
.onClick(async (event: ClickEvent, result: SaveButtonOnClickResult) => {
if (result == SaveButtonOnClickResult.SUCCESS) {
try {
componentSnapshot.get('snapshot'/*截图组件绑定的id*/, async (error: Error, pixelMap: image.PixelMap) => {
if (pixelMap) {
this.saveImage(pixelMap)
} else {
promptAction.showToast({message:'保存失败'})
}
}, {scale:0.5})
}
catch (error) {
promptAction.showToast({message:'保存失败'})
}
}
})
}
.height('100%')
.width('100%')
}
//保存图片
async saveImage(pixelMap: PixelMap) {
let imagePackerApi = image.createImagePacker();
const packOptions: image.PackingOption = {
format: 'image/jpeg',
quality: 100
}
imagePackerApi.packing(pixelMap, packOptions).then(async (buffer : ArrayBuffer) => {
//
try {
const context = getContext()
let helper = photoAccessHelper.getPhotoAccessHelper(context)
// onClick触发后10秒内通过createAsset接口创建图片文件,10秒后createAsset权限收回。
let uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpg')
let file = await fs.open(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
await fs.write(file.fd, buffer);
// 关闭文件
await fs.close(file.fd);
promptAction.showToast({message:'保存成功'})
}
catch (error) {
promptAction.showToast({message:'保存失败'})
}
}).catch((error : BusinessError) => {
promptAction.showToast({message:'保存失败'})
})
}
}
在HarmonyOS鸿蒙Next中,保存column中的内容到相册可以通过使用Image
和ImagePacker
类来实现。首先,确保你已经获取到column中的图像数据。假设你有一个PixelMap
对象,表示column中的图像内容。
使用ImagePacker
类可以将PixelMap
对象打包为图像文件。具体步骤如下:
- 创建
ImagePacker
实例。 - 使用
ImagePacker
的addImage
方法将PixelMap
对象添加到打包器中。 - 调用
ImagePacker
的setFormat
方法设置图像格式,如JPEG或PNG。 - 使用
ImagePacker
的setQuality
方法设置图像质量。 - 调用
ImagePacker
的startPacking
方法开始打包,并指定输出文件路径。
完成后,图像文件将被保存到指定路径。接下来,使用MediaLibrary
类将图像文件保存到相册中。具体步骤如下:
- 创建
MediaLibrary
实例。 - 使用
MediaLibrary
的getMediaAssets
方法获取媒体库的根目录。 - 使用
MediaLibrary
的createMediaAsset
方法在指定目录下创建媒体资源,并指定源文件路径。
完成后,图像文件将被保存到相册中。
在HarmonyOS鸿蒙Next中,将Column
中的内容保存到相册可以通过以下步骤实现:
- 截屏
Column
内容:使用PixelMap
或Snapshot
API对Column
进行屏幕截图,生成图像数据。 - 保存图像到相册:将生成的图像数据通过
MediaLibrary
API保存到设备的相册中。
具体代码示例:
// 假设column是你要截屏的组件
PixelMap pixelMap = Snapshot.takeSnapshot(column);
// 保存到相册
MediaLibrary mediaLibrary = MediaLibrary.getInstance(context);
mediaLibrary.saveImage(pixelMap, "image_name.jpg");
确保在config.json
中声明了ohos.permission.WRITE_MEDIA
权限。