qidao123.com技术社区-IT企服评测·应用市场

标题: 支持鸿蒙next的uts插件 [打印本页]

作者: 郭卫东    时间: 6 天前
标题: 支持鸿蒙next的uts插件
*本文共四个功能函数,相当于四个插件。作者为了偷懒写成了一个插件,调对应的函数即可。

1、chooseImageHarmony函数:拉起相册选择图片并转为Base64

2、takePhotoAndConvertToBase64函数:拉起相机拍照并转为Base64

3、openBrowser函数:打开外部的华为浏览器并跳转

4、openAppMarket函数:打开鸿蒙应用市肆并跳转

以下为实现的核心代码

index.uts

  1. import picker from '@ohos.file.picker';
  2. import fs from '@ohos.file.fs';
  3. import image from '@ohos.multimedia.image';
  4. import { ImageUtil } from '@pura/harmony-utils';
  5. import picker2 from '@ohos.multimedia.cameraPicker'
  6. import camera from '@ohos.multimedia.camera';
  7. import common from '@ohos.app.ability.common';
  8. // import { BusinessError } from '@ohos.base';
  9. import fileuri from '@ohos.file.fileuri';
  10. // import fs from '@ohos.file.fs';
  11. import { buffer } from '@kit.ArkTS';
  12. import { image as image2 } from '@kit.ImageKit';
  13. import { Want, common as common2 } from '@kit.AbilityKit';
  14. // 拉起相册选择图片并转为Base64
  15. export async function chooseImageHarmony(): Promise<string> {
  16.         let file: fs.File | null = null;
  17.         let imageSource: image.ImageSource | null = null;
  18.         let pixelMap: image.PixelMap | null = null;
  19.        
  20.         try {
  21.                 // 1. 调用文件选择器
  22.                 const photoPicker = new picker.PhotoViewPicker();
  23.                 const selectOptions: picker.PhotoSelectOptions = {
  24.                         maxSelectNumber: 1, // 限制只能选择 1 张图片
  25.                         MIMEType: picker.PhotoViewMIMETypes.IMAGE_TYPE, // 可选:限制图片类型
  26.                 };
  27.                 const fileResult = await photoPicker.select(selectOptions);
  28.                
  29.                 // 2. 获取到URI
  30.                 const uri = fileResult.photoUris[0];
  31.                
  32.                 // 3. 使用文件描述符
  33.                 file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  34.                
  35.                 // 4. 创建ImageSource并获取PixelMap
  36.                 imageSource = image.createImageSource(file.fd);
  37.                
  38.                 // 5. 获取图片属性来得到原始尺寸
  39.                 const imageInfo = await imageSource.getImageInfo();
  40.                 const originalWidth = imageInfo.size.width;
  41.                 const originalHeight = imageInfo.size.height;
  42.                
  43.                 // 6. 定义压缩选项 - 使用正确的类型声明
  44.                 const decodingOptions: image.DecodingOptions = {
  45.                     desiredSize: {
  46.                         width: Math.min(800, originalWidth),  // 不超过800px
  47.                         height: Math.round((Math.min(800, originalWidth) / originalWidth) * originalHeight)
  48.                     },
  49.                     desiredPixelFormat: image.PixelMapFormat.RGBA_8888,
  50.                     // 以下是必须包含的默认值
  51.                     desiredRegion: {
  52.                         size: { width: originalWidth, height: originalHeight },
  53.                         x: 0,
  54.                         y: 0
  55.                     },
  56.                     editable: false
  57.                 };
  58.                
  59.                 pixelMap = await imageSource.createPixelMap(decodingOptions);
  60.                
  61.                 // 7. 转换为Base64
  62.                 const base64Str: string = await ImageUtil.pixelMapToBase64Str(pixelMap);
  63.                
  64.                 return base64Str
  65.         } catch (error) {
  66.                 return ""
  67.         } finally {
  68.                 imageSource?.release()
  69.                 pixelMap?.release();
  70.                 // 关闭文件(使用 fs.close(file.fd))
  71.                 if (file?.fd !== undefined) {
  72.                         fs.close(file.fd); // ✅ HarmonyOS NEXT 使用 fs.close(fd)
  73.                 }
  74.         }
  75. }
  76. class CameraPosition {
  77.   cameraPosition: camera.CameraPosition;
  78.   saveUri: string;
  79.   constructor(cameraPosition: camera.CameraPosition, saveUri: string) {
  80.     this.cameraPosition = cameraPosition;
  81.     this.saveUri = saveUri;
  82.   }
  83. }
  84. // 拉起相机拍照并转为Base64
  85. export async function takePhotoAndConvertToBase64(): Promise<string> {
  86.         let base64Str = ''
  87.         // 获取上下文
  88.         const context = getContext() as common.Context;
  89.   const pathDir = context.filesDir;
  90.   // 文件临时路径
  91.   const filePath = pathDir + '/' + new Date().getTime() + '.jpg';
  92.        
  93.   fs.createRandomAccessFileSync(filePath, fs.OpenMode.CREATE);
  94.   const uri = fileuri.getUriFromPath(filePath);
  95.        
  96.   try {
  97.                 // 唤起相机
  98.     let pickerProfile = new CameraPosition(camera.CameraPosition.CAMERA_POSITION_BACK, uri);
  99.     await picker2.pick(context, [picker2.PickerMediaType.PHOTO], pickerProfile);
  100.     const file = await fs.open(uri, fs.OpenMode.READ_ONLY);
  101.                
  102.     const imageSource: image.ImageSource = image2.createImageSource(file.fd);
  103.     const imagePackerApi = image2.createImagePacker();
  104.     const packOpts: image.PackingOption = { format: "image/jpeg", quality: 70 };
  105.     const imageBuffer = await imagePackerApi.packing(imageSource, packOpts);
  106.     base64Str = buffer.from(imageBuffer).toString('base64');
  107.                 const base64Str2 = 'data:image/jpeg;base64,' + base64Str;
  108.     return base64Str2;
  109.   } catch (error) {
  110.     // let err = error as BusinessError;
  111.     console.error(`拍照失败`);
  112.     return '';
  113.   } finally {
  114.                
  115.         }
  116. }
  117. // 打开外部的华为浏览器并跳转
  118. export function openBrowser(url: string): void {
  119.   // 1. 获取正确的上下文
  120.   const context = getContext() as common2.UIAbilityContext;
  121.   // 2. 明确定义 Want 类型
  122.   const want: Want = {
  123.                 "action": "ohos.want.action.viewData",
  124.                 "entities": ["entity.system.browsable"],
  125.                 "uri": url,
  126.                 "type": "text/plain"
  127.   };
  128.   // 3. 正确处理 Promise 类型
  129.   context.startAbility(want)
  130.     .then((): void => {  // 明确指定返回类型
  131.       console.log('openUrl: successfully');
  132.     })
  133.     .catch((err: Error): void => {  // 明确指定返回类型和错误类型
  134.       console.error('openURL Failed:', err);
  135.     });
  136. }
  137. // 打开鸿蒙应用商店并跳转
  138. export function openAppMarket(url: string): void {
  139.         // 1. 获取正确的上下文
  140.         const context = getContext() as common2.UIAbilityContext;
  141.        
  142.   const appMarketWant: Want = {
  143.     uri: url,
  144.   };
  145.   context.startAbility(appMarketWant)
  146.     .then((): void => {
  147.       console.log('AppMarket opened successfully');
  148.     })
  149.     .catch((err: Error): void => {
  150.       console.error('Failed to open AppMarket:', err);
  151.     });
  152. }
复制代码
利用示例:

   导入插件:
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’)
  作者已经实现的功能,有任何疑问请在批评区讨论。


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 qidao123.com技术社区-IT企服评测·应用市场 (https://dis.qidao123.com/) Powered by Discuz! X3.4