HarmonyOS 鸿蒙Next Image组件加载网络图片后,如何将加载好的图片提取出来保存
HarmonyOS 鸿蒙Next Image组件加载网络图片后,如何将加载好的图片提取出来保存
Image组件加载网络图片后,如何将加载好的图片提取出来,避免保存时再次Http请求。
想要实现的是长按Image组件,触发SaveButton按钮,然后将图片保存至相册。
目前折中的办法是重新http请求一次
  SaveButton({ icon: SaveIconStyle.LINES, text: SaveDescription.SAVE_IMAGE, buttonType: ButtonType.Capsule })
    .onClick(async (event: ClickEvent, result: SaveButtonOnClickResult) => {
      if (result === SaveButtonOnClickResult.SUCCESS) {
        Logger.debug(‘即将保存:’ + this.imageURL)
        const context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
        // 免去权限申请和权限请求等环节,获得临时授权,保存对应图片
        // savePhotoToGallery(context);
        let helper = photoAccessHelper.getPhotoAccessHelper(context);
        try {
          http.createHttp().request(
            this.imageURL,
            { expectDataType: http.HttpDataType.ARRAY_BUFFER }
          ).then(async (res) => {
            console.info(‘res’, JSON.stringify(res))
            // 将图片资源转为像素图(PixelMap)
            let pixelMap = await image.createImageSource(res.result as ArrayBuffer).createPixelMap()
            // onClick触发后5秒内通过createAsset接口创建图片文件,5秒后createAsset权限收回。
            let uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE, ‘jpg’);
            // 使用uri打开文件,可以持续写入内容,写入过程不受时间限制
            let file = await fs.open(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
            let packOpts: image.PackingOption = { format: ‘image/png’, quality: 100 }
            const imagePacker: image.ImagePacker = image.createImagePacker();
            return imagePacker.packToFile(pixelMap, file.fd, packOpts).finally(() => {
              imagePacker.release(); //释放
              fs.close(file.fd);
              promptAction.showToast({
                message: this.imageURL + ‘图片已保存至相册’,
                duration: 2000
              });
            });
          }).catch((err: Error) => {
            Logger.debug(“请求图片时错误:” + JSON.stringify(err))
          })
        } catch (error) {
          const err: BusinessError = error as BusinessError;
          Logger.debug(Failed to save photo. Code is ${err.code}, message is ${err.message});
        }
      } else {
        promptAction.showToast({
          message: ‘设置权限失败!’,
          duration: 2000
        });
      }
    })
    .backgroundColor(Color.Blue)
}更多关于HarmonyOS 鸿蒙Next Image组件加载网络图片后,如何将加载好的图片提取出来保存的实战教程也可以访问 https://www.itying.com/category-93-b0.html
可将图片保存到APP沙箱中,下次从沙箱中读取即可。具体文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/app-sandbox-directory-V5
保存到APP沙箱中就有点麻烦了。image(url),这样写可以直接加载图片,Image组件对于相同的url也有防重复请求的机制,不用自己再去写http请求了,唯一不好的地方就是我想要保存或是使用这张图片的时候,不知道咋弄了(除了再请求一遍之外)。
在HarmonyOS开发中,若你已经使用Next Image组件成功加载了网络图片,并希望提取该图片进行保存,可以通过以下步骤实现:
- 
获取Bitmap对象:首先,确保你的Next Image组件已经加载完成图片。接着,通过
ImageProvider或类似方法获取到图片的Bitmap对象。这通常涉及对Image组件的图像处理接口进行调用,获取其当前显示的图像数据。 - 
保存Bitmap到文件:获取到
Bitmap对象后,你可以使用文件操作API将其保存为图片文件。选择合适的存储路径和文件格式(如JPEG、PNG),通过FileOutputStream和Bitmap.compress方法将Bitmap写入文件。 - 
处理权限:注意,保存文件到外部存储需要申请并处理相关权限(如WRITE_EXTERNAL_STORAGE)。确保你的应用在Manifest文件中声明了这些权限,并在运行时请求用户授权。
 - 
错误处理:在文件操作和图像处理过程中,添加必要的错误处理逻辑,以确保在出现异常时能够妥善处理。
 
如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html
        
      
                  
                  
                  

