HarmonyOS uniapp转H5保存相册和保存文件

uniapp转H5再套web,API不支持,需要手动适配保存相册和保存文件,有没有好的解决方案

比如API:uni.saveFile,保存文件到本地。

HarmonyOS
1天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
shlp

请参考以下demo:

import { image } from '@kit.ImageKit';
import util from '@ohos.util';
import pickers from '@ohos.file.picker';
import systemDateTime from '@ohos.systemDateTime';
import fs from '@ohos.file.fs';
import { buffer, JSON } from '@kit.ArkTS';
import photoAccessHelper from '@ohos.file.photoAccessHelper';

class imagetmp {
  codeImg: PixelMap | undefined = undefined
  set(val: PixelMap) {
    this.codeImg = val
    console.log('PixelMap=========' + val)
  }
}

@Entry
@Component
struct ImageDemo {
  @State resultBase64Str: string = '';
  @State getAlbum: string = '显示相册中的图片';
  @State pixel: image.PixelMap | undefined = undefined;
  @State albumPath: string = '';
  @State photoSize: number = 0;
  private base64Str: string = '';
  private settings: RenderingContextSettings = new RenderingContextSettings(true)
  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  @State pixelMap: PixelMap | undefined = undefined;

  build() {
    Scroll() {
      Column() {
        Canvas(this.context)
          .width('100%')
          .height('50%')
          .backgroundColor('#ffff00')
          .onReady(() => {
            // this.setWidth();
          })

        Image(this.pixelMap).width(200).height(200)
        Button('保存图片')
          .onClick(() => {
            this.save();
          })
        Button('获取图片')
          .onClick(async () => {
            await this.getPictureFromAlbum()
          })

        Image('https://xxx')
          .width('100%')
          .height('20%')

      }
    }
  }

  async getPictureFromAlbum() { // 拉起相册,选择图片
    let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
    PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
    PhotoSelectOptions.maxSelectNumber = 1;
    let photoPicker = new photoAccessHelper.PhotoViewPicker();
    let photoSelectResult: photoAccessHelper.PhotoSelectResult = await photoPicker.select(PhotoSelectOptions);
    this.albumPath = photoSelectResult.photoUris[0];
    console.info('albumPath: ' +
    this.albumPath) // 读取图片为buffer
    const file = fs.openSync(this.albumPath, fs.OpenMode.READ_WRITE);
    this.photoSize = fs.statSync(file.fd).size;
    console.info('Photo Size: ' + this.photoSize);
    let buffer1 = new ArrayBuffer(this.photoSize);

    fs.readSync(file.fd, buffer1);
    this.base64Str = buffer.from(buffer1).toString('base64')
    let resultBase64Str = "data:image/png;base64," + this.base64Str;
    console.log('base64Str---', this.base64Str)
    this.resultBase64Str = resultBase64Str
    fs.closeSync(file); // 解码成PixelMap
    const imageSource = image.createImageSource(buffer1);
    console.log('imageSource: ' + JSON.stringify(imageSource));

    let blob = new buffer.Blob([buffer1])
    console.log('blob---', JSON.stringify(blob));

  }

  setWidth() {

    const img: Uint8Array = getContext(this).resourceManager.getRawFileContentSync('ic_banner01.png');
    const imageSource: image.ImageSource = image.createImageSource(img.buffer);
    const PixelMap: image.PixelMap = imageSource.createPixelMapSync()
    PixelMap.scale(1.2, 1.2)

    const images = new ImageBitmap(PixelMap);
    const patter = this.context.createPattern(images, 'repeat')
    if (patter) {
      this.context.fillStyle = patter
    }
    this.context.fillRect(50, 50, 50, 50)

  }

  private async blobToImg(buffer: ArrayBuffer) {
    try {
      console.log('blobToImg===============' + buffer.toString())
      // let imageData: ArrayBuffer = OutData.result as ArrayBuffer;
      let imageSource: image.ImageSource = image.createImageSource(buffer);
      imageSource.getImageInfo().then((data) => {
        console.log('imageSource2===============' + data)
      })
      console.log('imageSource===============' + imageSource.getImageInfo())

      class tmp {
        height: number = 100
        width: number = 100
      }

      let si: tmp = new tmp()
      let options: Record<string, number | boolean | tmp> = {
        'alphaType': 2, // 透明度
        'editable': true, // 是否可编辑
        'pixelFormat': 4, // 像素格式
        'scaleMode': 1, // 缩略值
        'size': { height: 760, width: 1440 }
      } // 创建图片大小
      console.log('options=====', JSON.stringify(options));
      let json = JSON.stringify(options);
      let test: Record<string, number | boolean | tmp> = JSON.parse(json) as Record<string, number | boolean | tmp>;
      imageSource.createPixelMap(test).then((pixelMap: image.PixelMap) => {
        this.pixelMap = pixelMap;
        let im = new imagetmp()
        im.set(pixelMap)
      })
    } catch (err) {
      console.error(err)
    }
  }

  async save() {
    let pixelMap = await this.base64ToPixelMap1(this.base64Str)
    let arrayBuffer = new ArrayBuffer(3072 * 1024);
    pixelMap.readPixelsToBufferSync(arrayBuffer);

    let photoSaveOptions = new pickers.PhotoSaveOptions();
    let name = systemDateTime.getTime(true) + 'test.png';
    photoSaveOptions.newFileNames = [name];

    let photoPicker = new pickers.PhotoViewPicker(getContext(this));


    let photoSaveResult = await photoPicker.save(photoSaveOptions);
    console.log('photoSaveResult---', JSON.stringify(photoSaveResult))
    if (photoSaveResult.length == 0) {
      console.log('shibai--')
      return
    }

    let file = fs.openSync(photoSaveResult[0], fs.OpenMode.READ_WRITE);

    await fs.write(file.fd, arrayBuffer);
    fs.closeSync(file);
  }

  base64ToPixelMap1(base64: string): Promise<image.PixelMap> {
    // 将原始图片base64字符串转变为通过base64字符串
    // const reg = new RegExp('data:image/\\w+;base64,')
    // const base64Str = base64.replace(reg, '')
    // 将通用base64字符串转变为arrayBuffer
    let base64Helper = new util.Base64Helper();
    let uint8Array = base64Helper.decodeSync(base64)
    let arrayBuffer = uint8Array.buffer
    // 将arrayBuffer转变为pixelMap
    let imageSource = image.createImageSource(arrayBuffer)
    let opts: image.DecodingOptions = { editable: false }
    // 注意:这里return的是Promise,因此使用时需要在业务侧拿到最终的PixelMap
    return imageSource.createPixelMap(opts);
  }
}

权限配置加上:

"requestPermissions": [
{
  "name":
  "ohos.permission.CAMERA", "usedScene":
  {
    "abilities": [
    "EntryAbility" ],
    "when":
    "inuse"
  }
  ,
  "reason":
  "$string:CAMERA"
}
,
{
  "name":
  "ohos.permission.READ_IMAGEVIDEO", "usedScene":
  {
    "abilities": [
    "EntryAbility" ],
    "when":
    "inuse"
  }
  ,
  "reason":
  "$string:CAMERA"
}
,
{
  "name":
  "ohos.permission.WRITE_IMAGEVIDEO", "usedScene":
  {
    "abilities": [
    "EntryAbility" ],
    "when":
    "inuse"
  }
  ,
  "reason":
  "$string:CAMERA"
}
],
分享
微博
QQ
微信
回复
1天前
相关问题
HarmonyOS H5页面保存图片到本地相册
35浏览 • 1回复 待解决
HarmonyOS H5如何访问相册
305浏览 • 1回复 待解决
HarmonyOS H5原生交互
31浏览 • 1回复 待解决
HarmonyOS h5客服无法上传相册的图片
22浏览 • 1回复 待解决
HarmonyOS h5ArkTS通信
318浏览 • 1回复 待解决
HarmonyOS图片保存相册问题
465浏览 • 1回复 待解决
HarmonyOS h5HarmonyOS怎么通信?
186浏览 • 1回复 待解决
HarmonyOS webview 怎么H5交互
76浏览 • 1回复 待解决
HarmonyOS 获取h5的高度宽度
36浏览 • 1回复 待解决
HarmonyOS 截图保存图片到相册
34浏览 • 1回复 待解决
HarmonyOS 图片保存相册报错
28浏览 • 1回复 待解决
HarmonyOS 实现保存图片到相册
0浏览 • 0回复 待解决
Web中webviewH5交互
1115浏览 • 1回复 待解决
HarmonyOS web原生H5如何交互?
559浏览 • 1回复 待解决
HarmonyOS H5应用侧数据交互
310浏览 • 1回复 待解决
HarmonyOS ArkTSh5的数据解析
26浏览 • 1回复 待解决