HarmonyOS 如何把C++侧string类型的图片在TS中转换成图片格式?

C++侧把图片数据通过字节流转换成string传给TS侧,TS侧如何将这个string转换成pixelMap?

class DHData {
  public:
    explicit DHData(size_t capacity);
  ~DHData();
  size_t Size();
  size_t Offset();
  size_t Capacity();
  uint8_t *Data();
  int32_t SetRange(size_t offset, size_t size);
};
shared_ptr<DHData> data;
std::string controllData(data->Data(), data->Data()+data->Size());

C++侧代码如上,最终是把图片数据转换成了controllData这个string传给TS侧。

阅读 510
1 个回答

代码整理如下:

import { util } from '@kit.ArkTS';
import fs from '@ohos.file.fs';
import { BusinessError } from '@kit.BasicServicesKit';

const base64String =
  'iVBORw0KGgoAAAANSUhEUgAAAB4AAAAtCAMAAACOACuTAAAALVBMVEVMaXE2QU03QE02QU48PEs0Q0s2QU42Qk43QE43QU03QU04P043QE43QVA3QU7fFG+6AAAADnRSTlMAu3fuESKPVd1mzESqM0jcJEgAAACOSURBVHjatZBJEsAgCARV3BP5/3Oj3mdIZZlrF9CMs+Jx2sSKE/7FIEMmzYimRTuisS8aYRWTykA060xDtKipVelhLYiGRU+6WhJdHai1QK+6X6ZeFXYt9rBEOhzosCaqnfHPtO2TfpV0JXOxgXB/v5t7q0PZ1CN66I2+D3460q/lodkgpdjibeNm/fVtLk4YEK1O5uSkAAAAAElFTkSuQmCC';

@Entry
@Component
struct Index {
  @State imagestr: string = ''

  base64Image() {
    let begin = 'data:image/jpeg;base64,'
    return begin + base64String
  }

  aboutToAppear(): void {
    this.imagestr = this.base64Image()
  }

  build() {
    Row() {
      Column() {
        Image(this.imagestr).width(300).height(100).backgroundColor(Color.Green)
        Button("保存图片").onClick(() => {
          this.picture()
        })
      }.width('100%')
    }.height('100%')
  }

  picture() {
    let that = new util.Base64Helper();
    let result: Uint8Array = that.decodeSync(base64String, util.Type.MIME);
    let buf: ArrayBuffer = result.buffer as ArrayBuffer
    const context: Context = getContext(this);
    const path1: string = context.cacheDir + "/pixel_map1169.jpg";
    let file = fs.openSync(path1, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
    fs.write(file.fd, buf).then(async (writeLen) => {
      console.info("write data to file succeed and size is:" + writeLen);
      fs.closeSync(file);
    }).catch((err: BusinessError) => {
      console.info("write data to file failed with error message: " + err.message + ", error code: " + err.code);
    });
  }
} 
logo
HarmonyOS
子站问答
访问
宣传栏