HarmonyOS 鸿蒙Next pixMap转base64

发布于 1周前 作者 ionicwang 来自 鸿蒙OS

HarmonyOS 鸿蒙Next pixMap转base64

请问image.PixelMap类型的数据,转base64数据,怎么转

3 回复

PixelMap转base64:PixelMap转换成base64必须先使用imagePacker将pixelMap压缩后再进行base64,若要实现无损压缩,将PixelMap压缩成PNG,即调用imagePacker时,let packOpts: image.PackingOption = { format: ‘image/png’, quality: 100 };

参考如下代码:
let resourceManager = getContext(this).resourceManager
let imageArray = await resourceManager.getMediaContent($r('app.media.beer'));
let pixelBuffer = new Uint8Array(imageArray).buffer as Object as ArrayBuffer
let imageResource = image.createImageSource(pixelBuffer);
let opts: image.DecodingOptions = { editable: true }
let pixelMap = await imageResource.createPixelMap(opts);

// 转换成base64
const imagePackerApi: image.ImagePacker = image.createImagePacker();
let packOpts: image.PackingOption = { format: 'image/jpeg', quality: 100 };
imagePackerApi.packing(pixelMap, packOpts).then((data: ArrayBuffer) => {
let buf: buffer.Buffer = buffer.from(data);
this.base64 = 'data:image/jpeg;base64,' + buf.toString('base64', 0, buf.length);
console.info('base64: ' + this.base64);
})

更多关于HarmonyOS 鸿蒙Next pixMap转base64的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


import util from '@ohos.util';
import { image } from '@kit.ImageKit';
import fs from '@ohos.file.fs';
import buffer from '@ohos.buffer';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { FileUtils } from './FileUtils';
import { BusinessError } from '@kit.BasicServicesKit';
import picker from '@ohos.multimedia.cameraPicker';
import { camera } from '@kit.CameraKit'

export class ImageUtils {
  /***
   * 图片uri 转 base64 格式
   */
  static async uriConvertBase64(uri: string): Promise<string> {

    let pixelMap = await ImageUtils.uriOrPathConvertPixelMap(uri)
    if (pixelMap == undefined) {
      throw new Error(" uriConvertBase64 转换失败")
      return ''
    }
    return ImageUtils.pixMapConvertBase64(pixelMap)
  }

  /****
   * 图片 pixMap 转 base64 格式
   */
  static async pixMapConvertBase64(pixelMap: image.PixelMap, needPrefix: boolean = false): Promise<string> {
    const packOptions: image.PackingOption = {
      format: 'image/jpeg',
      quality: 60 // 图片质量不能过高,不然参数出问题
    }
    let arrayBuffer = await image.createImagePacker().packing(pixelMap, packOptions)
    let buf: buffer.Buffer = buffer.from(arrayBuffer);
    if (needPrefix) {
      return 'data:image/jpeg;base64,' + buf.toString('base64', 0, buf.length);
    } else {
      return buf.toString('base64', 0, buf.length);
    }
  }

  //
  static base64ToPixelMap(base64: string): Promise<image.PixelMap> {
    // 将原始图片base64字符串转变为通过base64字符串
    const reg = new RegExp('data:image/\\w+;base64,')
    const base64Str = base64.replace(reg, '')
    let helper = new util.Base64Helper();
    let buffer = helper.decodeSync(base64Str, util.Type.MIME).buffer as ArrayBuffer;
    let imageSource = image.createImageSource(buffer);
    let opts: image.DecodingOptions = { editable: true };
    return imageSource.createPixelMap(opts);
  }

  //uri/filePath 转 pixelMap
  static async uriOrPathConvertPixelMap(path: string): Promise<image.PixelMap | undefined> {
    try {
      let file = fs.openSync(path, fs.OpenMode.READ_ONLY)
      const imageSource: image.ImageSource = image.createImageSource(file.fd)
      fs.closeSync(file)
      let decodingOptions: image.DecodingOptions = {
        editable: true,
        desiredPixelFormat: 3,
      }
      let pixelMap = await imageSource.createPixelMap(decodingOptions)
      return pixelMap
    } catch (e) {
      return undefined
    }
  }

  static chooseImgFileToBase64(): Promise<string> {
    return new Promise((resolve: Function, reject: Function) => {
      try {
        let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
        photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
        photoSelectOptions.maxSelectNumber = 1;
        let photoPicker = new photoAccessHelper.PhotoViewPicker();
        photoPicker.select(photoSelectOptions).then((photoSelectResult: photoAccessHelper.PhotoSelectResult) => {
          if (photoSelectResult.photoUris.length <= 0) {
            resolve("")
            return
          }

          const ALBUM_PATH: string = photoSelectResult.photoUris[0]
          let buffer: ArrayBuffer = FileUtils.readFileOnly(ALBUM_PATH) as ArrayBuffer;
          // 通过缓冲区创建图片源实例
          const imageSource: image.ImageSource = image.createImageSource(buffer);

          const decodingOptions: image.DecodingOptions = {
            editable: true, // 是否可编辑。当取值为false时,图片不可二次编辑,如crop等操作将失败。
          }
          //const imageSource: image.ImageSource = image.createImageSource(buffer);
          imageSource.createPixelMap(decodingOptions).then((originalPixelMap: image.PixelMap) => {
            ImageUtils.pixMapConvertBase64(originalPixelMap).then((data: string) => {
              resolve(data)
            })
          })
            .catch((err: BusinessError) => {
              reject("")
            });
        }).catch((err: BusinessError) => {
          reject("")
        });
      } catch (error) {
        let err: BusinessError = error as BusinessError;
        reject("")
      }
    })
  }

  static takePhotoToBase64(): Promise<string> {
    return new Promise(async (resolve: Function, reject: Function) => {
      try {
        let pickerProfile: picker.PickerProfile = {
          cameraPosition: camera.CameraPosition.CAMERA_POSITION_BACK // 后置摄像头
        };
        let res: picker.PickerResult = await picker.pick(getContext(),
          [picker.PickerMediaType.PHOTO], pickerProfile);
        if (!res.resultUri.length) {
          return
        }
        const ALBUM_PATH: string = res.resultUri
        let buffer: ArrayBuffer = FileUtils.readFileOnly(ALBUM_PATH) as ArrayBuffer;
        // 通过缓冲区创建图片源实例
        const imageSource: image.ImageSource = image.createImageSource(buffer);

        const decodingOptions: image.DecodingOptions = {
          editable: true, // 是否可编辑。当取值为false时,图片不可二次编辑,如crop等操作将失败。
        }
        //const imageSource: image.ImageSource = image.createImageSource(buffer);
        imageSource.createPixelMap(decodingOptions).then((originalPixelMap: image.PixelMap) => {
          ImageUtils.pixMapConvertBase64(originalPixelMap).then((data: string) => {
            resolve(data)
          })
        })
          .catch((err: BusinessError) => {
            reject("")
          });
      } catch (error) {
        let err: BusinessError = error as BusinessError;
        reject("")
      }
    })
  }

  async base64ImgConvertFilePath(context: Context, base64Str: string): Promise<string | undefined> {
    try {
      const filePath = context.cacheDir + "/xxx_" + new Date().getTime() + '.png';

      let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
      const reg = new RegExp("data:image/\\w+;base64,")
      const base64 = base64Str.replace(reg, "");
      const dataBuffer = buffer.from(base64, 'base64').buffer;
      const size = fs.writeSync(file.fd, dataBuffer);
      //关闭文件
      fs.closeSync(file);
      return filePath
    } catch (error) {
      return undefined
    }
  }
}

在HarmonyOS中,将nextPixMap对象转换为Base64字符串涉及几个步骤,包括将像素数据提取为字节数组,然后将该字节数组编码为Base64字符串。以下是实现此转换的简要方法:

  1. 获取像素数据:首先,你需要从nextPixMap对象中获取像素数据。这通常包括像素的位图数据及其尺寸信息。

  2. 转换为字节数组:将获取的像素数据(如RGBA或ARGB格式)转换为字节数组。这通常涉及将像素数据从位图格式复制到字节数组中。

  3. Base64编码:使用HarmonyOS提供的Base64编码工具,将字节数组编码为Base64字符串。HarmonyOS的API中可能包含此类编码工具,或者你可以使用第三方库。

示例代码(伪代码,具体实现需参考HarmonyOS API文档):

// 假设你已经有了nextPixMap对象
PixMap pixMap = getNextPixMap();
ByteBuffer pixelData = getPixelDataFromPixMap(pixMap);
byte[] byteArray = pixelData.array();

// 使用HarmonyOS Base64编码工具
String base64String = Base64.encodeToString(byteArray, Base64.DEFAULT);

// base64String 现在包含了转换后的Base64字符串

注意:上述代码为简化示例,实际实现需根据HarmonyOS的API文档进行调整。如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html

回到顶部