HarmonyOS 是否可以获取系统Image组件对网络图片的缓存

1、原生Image加载过的图片是否可以通过url等链接获取ArrayBuffer。

2.、如果不能,这种场景应该怎么处理缓存共享?

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

可以,网络请求下载图片将网络地址成功返回的数据,编码转码成pixelMap的图片格式,pixelMap经过packing装成arraybuffer,获取getPhotoAccessHelper写入文件,参考示例:

import http from '@ohos.net.http';
import ResponseCode from '@ohos.net.http';
import image from '@ohos.multimedia.image';
import { BusinessError } from '@ohos.base';
import photoAccessHelper from '@ohos.file.photoAccessHelper'
import fs from '@ohos.file.fs'

@Entry
@Component
struct Index {
  @State pixelMap: PixelMap | undefined = undefined;

  loadImageWithUrl(url: string) {
    let OutData: http.HttpResponse
    let imagePackerApi = image.createImagePacker();
    let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 };
    //确保网络正常
    http.createHttp().request(url,
      {
        method: http.RequestMethod.GET,
        connectTimeout: 60000,
        readTimeout: 60000

      },
      async (error: BusinessError, data: http.HttpResponse) => {
        if (error) {
          console.error(`http reqeust failed with. Code: ${error.code}, message: ${error.message}`);
        } else {
          OutData = data
          let code: http.ResponseCode | number = OutData.responseCode
          if (ResponseCode.ResponseCode.OK === code) {
            let imageData: ArrayBuffer = OutData.result as ArrayBuffer;
            let imageSource: image.ImageSource = image.createImageSource(imageData);

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

            let si: tmp = new tmp()
            let options: Record<string, number | boolean | tmp> = {
              'alphaType': 0, // 透明度
              'editable': false, // 是否可编辑
              'pixelFormat': 3, // 像素格式
              'scaleMode': 1, // 缩略值
              'size': { height: 100, width: 100 }
            } // 创建图片大小
            imageSource.createPixelMap(options).then((pixelMap: PixelMap) => {
              this.pixelMap = pixelMap
              this.pixelMap.getImageInfo().then((info: image.ImageInfo) => {
                console.info('info.width = ' + info.size.width)
              }).catch((err: BusinessError) => {
                console.error("Faild " + err);
              })
              imagePackerApi.packing(pixelMap, packOpts).then(async (buffer: ArrayBuffer) => {
                //
                try {
                  const context = getContext(this)
                  let helper = photoAccessHelper.getPhotoAccessHelper(context)
                  let uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'png')
                  let file = await fs.open(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
                  //let buffer = new ArrayBuffer(this.pixelMap!.getPixelBytesNumber())
                  // await this.image!.readPixelsToBuffer(buffer)
                  // 写入文件   注意加一个packing的过程
                  await fs.write(file.fd, buffer);
                  // 关闭文件
                  await fs.close(file.fd);
                  console.log("imagePackerApi packing")
                } catch (error) {
                  console.error("error is " + JSON.stringify(error))
                }

              }).catch((error: BusinessError) => {
                console.error('Failed to pack the image. And the error is: ' + error);
              })

              pixelMap.release();
            })
          }
        }
      }
    )
  }

  build() {
    Row() {
      Column() {
        Button("点击下载并保存网络图片", { type: ButtonType.Capsule, stateEffect: false })
          .width('100%')
          .height(55)
          .fontSize('15fp')
          .fontColor('#ffffff')
          .margin({ top: 20 })
          .onClick(() => {
            this.loadImageWithUrl("xxx")

          })
      }
      .width('100%')
    }
    .height('100%')
  }
}
分享
微博
QQ
微信
回复
1天前
相关问题
HarmonyOS Image组件网络图片缓存
56浏览 • 1回复 待解决
HarmonyOS Image组件网络图片不显示
441浏览 • 1回复 待解决
Image组件如何加载网络图片
2689浏览 • 1回复 待解决
HarmonyOS Image组件无法显示网络图片
1150浏览 • 1回复 待解决
服务卡片image怎么获取网络图片
7032浏览 • 2回复 待解决
关于Image组件加载网络图片问题
649浏览 • 1回复 待解决
HarmonyOS Image 加载网络图片问题
804浏览 • 1回复 待解决
HarmonyOS 获取网络图片PixelMap
39浏览 • 1回复 待解决