获取网络图片并保存到相册

后台返回了图片的地址,需要将该图片保存到系统相册。

HarmonyOS
2024-05-28 20:18:14
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
spitter

使用的核心API

1. 网络请求下载图片

2. 将网络地址成功返回的数据,编码转码成pixelMap的图片格式。

3. pixelMap经过packing装成arraybuffer

4. 获取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); 
                }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("https://copyright.bdstatic.com/vcg/creative/cc9c744cf9f7c864889c563cbdeddce6.jpg@h_1280") 
  
          }) 
      } 
      .width('100%') 
    } 
    .height('100%') 
  } 
}

注明适配的版本信息

  • IDE:DevEco Studio 4.0.3.600
  • SDK:HarmoneyOS 4.0.10.11
分享
微博
QQ
微信
回复
2024-05-29 21:18:10
相关问题
如何保存网络图片相册
175浏览 • 1回复 待解决
有谁知道如何将图片保存到相册
389浏览 • 1回复 待解决
服务卡片image怎么获取网络图片
5534浏览 • 2回复 待解决
怎么把视频保存到相册以及主机端?
2511浏览 • 1回复 待解决
如何将视频保存到相册以及主机端
4005浏览 • 1回复 待解决
页面加载前获取网络图片的宽高
198浏览 • 1回复 待解决
怎么下载网络上PDF保存到本地?
2256浏览 • 1回复 待解决
应用内组件截图保存到用户文件
126浏览 • 1回复 待解决
Image组件如何加载网络图片
892浏览 • 1回复 待解决
如何保存本地图片相册
175浏览 • 1回复 待解决
把应用沙箱下的图片保存到图库
357浏览 • 1回复 待解决
求大佬告知如何保存图片相册
285浏览 • 1回复 待解决
如何将像素点保存到图片文件
883浏览 • 1回复 待解决
如何保存一张PNG图片相册
419浏览 • 1回复 待解决
请问Image控件是怎样设置网络图片
8855浏览 • 3回复 已解决
图片压缩保存方法,有人知道吗?
299浏览 • 0回复 待解决