*本文共四个功能函数,相当于四个插件。作者为了偷懒写成了一个插件,调对应的函数即可。
1、chooseImageHarmony函数:拉起相册选择图片并转为Base64
2、takePhotoAndConvertToBase64函数:拉起相机拍照并转为Base64
3、openBrowser函数:打开外部的华为浏览器并跳转
4、openAppMarket函数:打开鸿蒙应用商店并跳转
以下为实现的核心代码
index.uts
import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs';
import image from '@ohos.multimedia.image';
import { ImageUtil } from '@pura/harmony-utils';
import picker2 from '@ohos.multimedia.cameraPicker'
import camera from '@ohos.multimedia.camera';
import common from '@ohos.app.ability.common';
// import { BusinessError } from '@ohos.base';
import fileuri from '@ohos.file.fileuri';
// import fs from '@ohos.file.fs';
import { buffer } from '@kit.ArkTS';
import { image as image2 } from '@kit.ImageKit';
import { Want, common as common2 } from '@kit.AbilityKit';
// 拉起相册选择图片并转为Base64
export async function chooseImageHarmony(): Promise<string> {
let file: fs.File | null = null;
let imageSource: image.ImageSource | null = null;
let pixelMap: image.PixelMap | null = null;
try {
// 1. 调用文件选择器
const photoPicker = new picker.PhotoViewPicker();
const selectOptions: picker.PhotoSelectOptions = {
maxSelectNumber: 1, // 限制只能选择 1 张图片
MIMEType: picker.PhotoViewMIMETypes.IMAGE_TYPE, // 可选:限制图片类型
};
const fileResult = await photoPicker.select(selectOptions);
// 2. 获取到URI
const uri = fileResult.photoUris[0];
// 3. 使用文件描述符
file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
// 4. 创建ImageSource并获取PixelMap
imageSource = image.createImageSource(file.fd);
// 5. 获取图片属性来得到原始尺寸
const imageInfo = await imageSource.getImageInfo();
const originalWidth = imageInfo.size.width;
const originalHeight = imageInfo.size.height;
// 6. 定义压缩选项 - 使用正确的类型声明
const decodingOptions: image.DecodingOptions = {
desiredSize: {
width: Math.min(800, originalWidth), // 不超过800px
height: Math.round((Math.min(800, originalWidth) / originalWidth) * originalHeight)
},
desiredPixelFormat: image.PixelMapFormat.RGBA_8888,
// 以下是必须包含的默认值
desiredRegion: {
size: { width: originalWidth, height: originalHeight },
x: 0,
y: 0
},
editable: false
};
pixelMap = await imageSource.createPixelMap(decodingOptions);
// 7. 转换为Base64
const base64Str: string = await ImageUtil.pixelMapToBase64Str(pixelMap);
return base64Str
} catch (error) {
return ""
} finally {
imageSource?.release()
pixelMap?.release();
// 关闭文件(使用 fs.close(file.fd))
if (file?.fd !== undefined) {
fs.close(file.fd); // ✅ HarmonyOS NEXT 使用 fs.close(fd)
}
}
}
class CameraPosition {
cameraPosition: camera.CameraPosition;
saveUri: string;
constructor(cameraPosition: camera.CameraPosition, saveUri: string) {
this.cameraPosition = cameraPosition;
this.saveUri = saveUri;
}
}
// 拉起相机拍照并转为Base64
export async function takePhotoAndConvertToBase64(): Promise<string> {
let base64Str = ''
// 获取上下文
const context = getContext() as common.Context;
const pathDir = context.filesDir;
// 文件临时路径
const filePath = pathDir + '/' + new Date().getTime() + '.jpg';
fs.createRandomAccessFileSync(filePath, fs.OpenMode.CREATE);
const uri = fileuri.getUriFromPath(filePath);
try {
// 唤起相机
let pickerProfile = new CameraPosition(camera.CameraPosition.CAMERA_POSITION_BACK, uri);
await picker2.pick(context, [picker2.PickerMediaType.PHOTO], pickerProfile);
const file = await fs.open(uri, fs.OpenMode.READ_ONLY);
const imageSource: image.ImageSource = image2.createImageSource(file.fd);
const imagePackerApi = image2.createImagePacker();
const packOpts: image.PackingOption = { format: "image/jpeg", quality: 70 };
const imageBuffer = await imagePackerApi.packing(imageSource, packOpts);
base64Str = buffer.from(imageBuffer).toString('base64');
const base64Str2 = 'data:image/jpeg;base64,' + base64Str;
return base64Str2;
} catch (error) {
// let err = error as BusinessError;
console.error(`拍照失败`);
return '';
} finally {
}
}
// 打开外部的华为浏览器并跳转
export function openBrowser(url: string): void {
// 1. 获取正确的上下文
const context = getContext() as common2.UIAbilityContext;
// 2. 明确定义 Want 类型
const want: Want = {
"action": "ohos.want.action.viewData",
"entities": ["entity.system.browsable"],
"uri": url,
"type": "text/plain"
};
// 3. 正确处理 Promise 类型
context.startAbility(want)
.then((): void => { // 明确指定返回类型
console.log('openUrl: successfully');
})
.catch((err: Error): void => { // 明确指定返回类型和错误类型
console.error('openURL Failed:', err);
});
}
// 打开鸿蒙应用商店并跳转
export function openAppMarket(url: string): void {
// 1. 获取正确的上下文
const context = getContext() as common2.UIAbilityContext;
const appMarketWant: Want = {
uri: url,
};
context.startAbility(appMarketWant)
.then((): void => {
console.log('AppMarket opened successfully');
})
.catch((err: Error): void => {
console.error('Failed to open AppMarket:', err);
});
}
使用示例:
导入插件:
import { chooseImageHarmony, takePhotoAndConvertToBase64, openBrowser, openAppMarket } from “@/uni_modules/ywx-getImageToBase64”;
调用函数:
1、const base64Data = await chooseImageHarmony();
2、const base64Data = await takePhotoAndConvertToBase64();
3、openBrowser(“https://hmapp.gisgm.cn/tdjg”)
4、openAppMarket(“store://appgallery.huawei.com/app/detail?id=” + ‘com.example.shilrey’)