当前位置: 首页 > news >正文

支持鸿蒙next的uts插件

*本文共四个功能函数,相当于四个插件。作者为了偷懒写成了一个插件,调对应的函数即可。

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. 获取到URIconst uri = fileResult.photoUris[0];// 3. 使用文件描述符file = fs.openSync(uri, fs.OpenMode.READ_ONLY);// 4. 创建ImageSource并获取PixelMapimageSource = 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),  // 不超过800pxheight: 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. 转换为Base64const 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’)

作者已经实现的功能,有任何疑问请在评论区讨论。

相关文章:

  • 计算机学习路线与编程语言选择(信息差)
  • LLaMA模型本地部署全攻略:从零搭建私有化AI助手
  • 突破网络限制:Windows平台离线搭建Linux环境+Docker化部署AI知识库RAGFlow实战
  • 平板收银系统、国产系统,鸿蒙系统,小键盘的封装与应用—仙盟创梦IDE
  • Matlab 数控车床进给系统的建模与仿真
  • Java执行linux服务器本地命令
  • HTTP Error 500.31 - Failed to load ASP.NET Core runtime
  • 第三节第一部分:Static修饰类变量、成员变量
  • xiaopiu原型设计工具笔记
  • 多环串级PID
  • Spring Boot 启动原理的核心机制
  • Git实战经验分享:深入掌握git commit --amend的进阶技巧
  • 一种机载扫描雷达实时超分辨成像方法——论文阅读
  • uniapp|实现多终端视频弹幕组件、内容轮询、信息表情发送(自定义全屏半屏切换、弹幕启用)
  • k8s(11) — 探针和钩子
  • 【Redis】持久化与事务
  • 电容的基本介绍
  • iNeuOS工业互联网操作系统,集成DeepSeek大模型应用
  • C#串口通信
  • 前端面试每日三题 - Day 28
  • 王受文已任全国工商联党组成员
  • 泽连斯基称与特朗普通话讨论停火事宜
  • 绍兴柯桥:用一块布托起中国制造的新经纬
  • 王日春已任教育部社会科学司司长,此前系人教社总编辑
  • 上海营商环境的“分寸”感:底线之上不断拓宽自由,底线之下雷霆制止
  • 外交部:印巴都表示不希望局势升级,望双方都能保持冷静克制