鸿蒙中相册图片暂存到沙箱,获取图片信息
·
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { BusinessError, request } from '@kit.BasicServicesKit';
import { fileIo } from '@kit.CoreFileKit';
import { http } from '@kit.NetworkKit';
import { image } from '@kit.ImageKit';
// fs.copyFileSync
@Entry
@Component
struct Index {
// 自定义生成的文件名
fileName: string = ""
// 图片类型
fileType: string = "jpg"
async loadPixelMap(uri: string) {
let pixelMap: image.PixelMap
// const imageSource = image.createImageSource("/data/storage/el2/base/haps/entry/cache/1753932557047.jpg");
const imageSource = image.createImageSource(uri);
pixelMap = await imageSource.createPixelMap();
pixelMap.getImageInfo().then((imageInfo: image.ImageInfo) => {
if (imageInfo != undefined) {
console.info("Succeeded in obtaining the image pixel map information." + JSON.stringify(imageInfo));
}
}).catch((error: BusinessError) => {
console.error(`Failed to obtain the image pixel map information. code is ${error.code}, message is ${error.message}`);
})
}
build() {
Column() {
Button("1 选择图片")
.onClick(async () => {
try {
// 创建一个新的 PhotoSelectOptions 实例来配置图片选择器的行为
let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
// 设置 MIME 类型为图像类型,这样用户只能选择图像文件
PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
// 设置用户可以选择的最大图片数量为 1 张
PhotoSelectOptions.maxSelectNumber = 1;
// PhotoSelectOptions.isSearchSupported = false
// 创建一个新的 PhotoViewPicker 实例,用于打开图片选择器
let photoPicker = new photoAccessHelper.PhotoViewPicker();
// 使用前面配置好的选项打开图片选择器,并等待用户完成选择
// 注意这里的 select 方法是一个异步方法,所以需要使用 await 关键字等待其结果
const PhotoSelectResult = await photoPicker.select(PhotoSelectOptions);
// `file://media/Photo/1/IMG_1725939294_000/screenshot_20240910_113314.jpg`
// 假设这里只关心用户选择的第一张图片
// 三.将文件保存到缓存目录(只能上传在缓存目录中的文件)
const context = getContext(this) // 上下文对象 程序运行过程中
// 生成一个新的文件名 234342343243.jpg
this.fileName = Date.now() + '.' + this.fileType
// 获取这个相册图片文件的权限 读取权限
const file = fileIo.openSync(PhotoSelectResult.photoUris[0], fileIo.OpenMode.READ_ONLY)
// 将文件 拷贝到 临时目录
// 通过缓存路径+文件名 拼接出完整的路径
// /data/storage/el2/base/haps/entry/cache/ 1726038971043.jpg
const copyFilePath = context.cacheDir + '/' + this.fileName
console.log('halsdjlasd=====' + copyFilePath)
// 拷贝文件
// file.fd 待复制的文件 文件描述符 数字
// copyFilePath 文件复制到哪去
fileIo.copyFileSync(file.fd, copyFilePath)
this.loadPixelMap(copyFilePath)
} catch (error) {
// 如果在 try 块中发生了错误,则会在这里捕获到这个错误
// 将捕获到的错误转换成 BusinessError 类型(假设 error 是一个继承自 Error 的自定义错误类型)
// 在控制台中打印错误信息,包括错误码和错误消息
console.error(`PhotoViewPicker failed with err: ${error.code}, ${error.message}`);
}
})
}
.width("100%")
.height("100%")
.justifyContent(FlexAlign.Center)
}
}
图片有关的信息
![]()
更多推荐



所有评论(0)