HarmonyOS 如何访问图片url,下载到图库?图片超过5M?

HarmonyOS 如何访问图片url,下载到图库?图片超过5M?

HarmonyOS
2024-11-08 09:04:46
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
put_get

​超过5M限制的,只需要改下maxlimit参数,参考文档:​https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis-network-kit/js-apis-http.md#httprequestoptions

代码片段如下:​

let httpRequest = http.createHttp(); 
let options: http.HttpRequestOptions = { 
  method: http.RequestMethod.GET, // 可选,默认为http.RequestMethod.GET 
  readTimeout: 60000, // 可选,默认为60000ms 
  connectTimeout: 60000, // 可选,默认为60000ms 
  maxLimit: 10*1024*1024 
};
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

以下是完整的demo。

//Index.ets 
import { photoAccessHelper } from '@kit.MediaLibraryKit'; 
import { abilityAccessCtrl, common, Permissions } from '@kit.AbilityKit'; 
import { http } from '@kit.NetworkKit'; 
import { BusinessError } from '@kit.BasicServicesKit'; 
import { promptAction } from '@kit.ArkUI'; 
import { image } from '@kit.ImageKit'; 
import fs from '@ohos.file.fs'; 
import { picker } from '@kit.CoreFileKit'; 
 
const PERMISSIONS: Array<Permissions> = [ 
  'ohos.permission.READ_MEDIA', 
  'ohos.permission.WRITE_MEDIA' 
]; 
@Entry 
@Component 
struct Index { 
  @State image:PixelMap | undefined = undefined 
  @State photoAccessHelper: photoAccessHelper.PhotoAccessHelper | undefined = undefined; 
  @State imageBuffer: ArrayBuffer | undefined = undefined; // 图片ArrayBuffer 
  getPicture() { 
    let httpRequest = http.createHttp(); 
    let options: http.HttpRequestOptions = { 
      method: http.RequestMethod.GET, // 可选,默认为http.RequestMethod.GET 
      readTimeout: 60000, // 可选,默认为60000ms 
      connectTimeout: 60000, // 可选,默认为60000ms 
      maxLimit: 10*1024*1024 
    }; 
    httpRequest.request('https://xxx.xxx.huawei.com/xxx/77a0-1400541358/9729-1/xxx.jpg',options, 
      (error:BusinessError,data:http.HttpResponse) => { 
        if(error) { 
          promptAction.showToast({ 
            message:('下载失败'), 
            duration:2000 
          }) 
          return 
        } 
        this.transcodePixelMap(data); 
        // 判断网络获取到的资源是否为ArrayBuffer类型 
        if (data.result instanceof ArrayBuffer) { 
          console.log('data.result'+JSON.stringify(data.result)) 
          this.imageBuffer = data.result as ArrayBuffer; 
        } 
      } 
    ) 
  } 
 
  /** 
   * 使用createPixelMap将ArrayBuffer类型的图片装换为PixelMap类型 
   * @param data:网络获取到的资源 
   */ 
  transcodePixelMap(data: http.HttpResponse) { 
    if(data.responseCode === 200) { 
      let imageData:ArrayBuffer = data.result as ArrayBuffer 
      // 通过ArrayBuffer创建图片源实例 
      let imageSource:image.ImageSource = image.createImageSource(imageData) 
      let option:image.InitializationOptions = { 
        'alphaType': 0, // 透明度 
        'editable': false, // 是否可编辑 
        'pixelFormat': 3, // 像素格式 
        'scaleMode': 1, // 缩略值 
        'size': { height: 100, width: 100 } 
      } 
      imageSource.createPixelMap(option).then((pixelMap:PixelMap) => { 
        this.image = pixelMap 
      }) 
    } 
  } 
 
  async aboutToAppear(): Promise<void> { 
    let context = getContext(this) as common.UIAbilityContext 
    let atManager = abilityAccessCtrl.createAtManager(); 
    await atManager.requestPermissionsFromUser(context,PERMISSIONS) 
    this.getPicture() 
  } 
  async saveImage(buffer:ArrayBuffer | string):Promise<void> { 
    let context = getContext(this) as common.UIAbilityContext 
    let helper = photoAccessHelper.getPhotoAccessHelper(context) 
    let uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE,'jpg') 
    let file = await fs.open(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 
    await fs.write(file.fd,buffer) 
    await fs.close(file.fd) 
  } 
  async pickerSave(buffer: ArrayBuffer | string): Promise<void> { 
    const photoSaveOptions = new picker.PhotoSaveOptions(); // 创建文件管理器保存选项实例 
    photoSaveOptions.newFileNames = ['PhotoViewPicker ' + new Date().getTime() + '.jpg'];// 保存文件名(可选) 
    const photoViewPicker = new picker.PhotoViewPicker; 
    photoViewPicker.save(photoSaveOptions) 
      .then(async (photoSaveResult) => { 
        console.info('PhotoViewPicker.save successfully,photoSaveResult uri:' + JSON.stringify(photoSaveResult)); 
        let uri = photoSaveResult[0]; 
        let file = await fs.open(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 
        await fs.write(file.fd, buffer); 
        await fs.close(file.fd); 
        promptAction.showToast({ 
          message: '保存成功', 
          duration: 2000 
        }) 
      }); 
  } 
 
  build() { 
    Row() { 
      Column() { 
        // 获取网络图片 
        Image(this.image) 
          .width(200) 
          .height(200) 
          .objectFit(ImageFit.Contain) 
        SaveButton() 
          .width(100) 
          .onClick(async () => { 
            if (this.imageBuffer !== undefined) { 
              await this.saveImage(this.imageBuffer); 
              promptAction.showToast({ 
                message: '保存成功', 
                duration: 2000 
              }) 
            } 
          }) 
        Button('保存') 
          .margin({ top: '20vp' }) 
          .height('100vp') 
          .onClick(async () => { 
            if (this.imageBuffer !== undefined) { 
              this.pickerSave(this.imageBuffer); 
            } 
          }) 
      } 
      .width('100%') 
    } 
    .height('100%') 
  } 
} 
 
//photoPicker.ets文件 
import { BusinessError } from '@ohos.base'; 
import picker from '@ohos.file.picker'; 
import { abilityAccessCtrl, common, Permissions } from '@kit.AbilityKit'; 
import { photoAccessHelper } from '@kit.MediaLibraryKit'; 
import fs from '@ohos.file.fs'; 
import { image } from '@kit.ImageKit'; 
import { buffer, util } from '@kit.ArkTS'; 
const PERMISSIONS: Array<Permissions> = [ 
  'ohos.permission.READ_MEDIA', 
  'ohos.permission.WRITE_MEDIA' 
]; 
@Entry 
@Component 
struct SelectPictures { 
  async getFileAssetsFromType() { 
    let context = getContext(this) as common.UIAbilityContext 
    let atManager = abilityAccessCtrl.createAtManager(); 
    await atManager.requestPermissionsFromUser(context,PERMISSIONS) 
    const photoSelectOption = new picker.PhotoSelectOptions() 
    photoSelectOption.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE 
    photoSelectOption.maxSelectNumber = 2 
    const photoViewPicker = new picker.PhotoViewPicker 
    photoViewPicker.select(photoSelectOption).then(async (photoSelectResult) => { 
      this.uris = photoSelectResult.photoUris 
      this.photoCount = this.uris[0].length 
    }).catch((err: BusinessError) => { 
      console.info('Invoke photoViewPicker.select failed, code is ${err.code},message is ${err.message}'); 
    }) 
  } 
  @State uris: Array<string> = []; // 全局变量保存图库选择的结果uri 
  @State photoCount: number = 0; // 全局变量控制选择图片的显示 
  @State pixelMap:PixelMap | undefined = undefined 
  build() { 
    Column() { 
      Image(this.pixelMap) 
        .width('50%') 
        .height('30%') 
      Image(this.photoCount > 0 ? this.uris[0] : $r('app.media.add')) 
        .objectFit(this.photoCount > 0 ? ImageFit.Contain : ImageFit.None) 
        .width('50%') 
        .height('30%') 
        .onClick(() => { 
          // TODO:知识点:通过调用getFileAssetsFromType()中的photoViewPicker.select()拉起图库界面进行图片选择。 
          this.getFileAssetsFromType(); 
        }) 
        .margin({ bottom: '20vp' }) 
 
      // 接photoPicker.ets文件 
      Image(this.photoCount > 1 ? this.uris[1] : '') 
        .visibility(this.photoCount > 1 ? Visibility.Visible : Visibility.None) 
        .objectFit(this.photoCount > 1 ? ImageFit.Contain : ImageFit.None) 
        .width('50%') 
        .height('30%') 
        .onClick(() => { 
          // TODO:知识点:通过调用getFileAssetsFromType()中的photoViewPicker.select()拉起图库界面进行图片选择。 
          this.getFileAssetsFromType(); 
        }) 
      SaveButton() 
        .width(100) 
        .onClick(async () => { 
          let file = fs.openSync(this.uris[0], fs.OpenMode.READ_ONLY) 
          const imageSource = image.createImageSource(file.fd); 
          fs.closeSync(file) 
          const imagePackApi = image.createImagePacker() 
          let packOpts: image.PackingOption = { format: "image/png", quality: 100 } 
          imagePackApi.packing(imageSource, packOpts) 
            .then(async readBuffer => { 
              let imageSource:image.ImageSource = image.createImageSource(readBuffer as ArrayBuffer) 
              let option:image.InitializationOptions = { 
                'alphaType': 0, // 透明度 
                'editable': false, // 是否可编辑 
                'pixelFormat': 3, // 像素格式 
                'scaleMode': 1, // 缩略值 
                'size': { height: 100, width: 100 } 
              } 
              imageSource.createPixelMap(option).then((pixelMap:PixelMap) => { 
                this.pixelMap = pixelMap 
              }).catch((err:BusinessError) => { 
                console.error('PhotoViewPicker.select failed with err: ' + err); 
              }) 
            }).catch((err:BusinessError) => { 
            console.error('PhotoViewPicker.select failed with err: ' + err); 
          }) 
        }) 
    } 
    .margin('20vp') 
  } 
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102.
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108.
  • 109.
  • 110.
  • 111.
  • 112.
  • 113.
  • 114.
  • 115.
  • 116.
  • 117.
  • 118.
  • 119.
  • 120.
  • 121.
  • 122.
  • 123.
  • 124.
  • 125.
  • 126.
  • 127.
  • 128.
  • 129.
  • 130.
  • 131.
  • 132.
  • 133.
  • 134.
  • 135.
  • 136.
  • 137.
  • 138.
  • 139.
  • 140.
  • 141.
  • 142.
  • 143.
  • 144.
  • 145.
  • 146.
  • 147.
  • 148.
  • 149.
  • 150.
  • 151.
  • 152.
  • 153.
  • 154.
  • 155.
  • 156.
  • 157.
  • 158.
  • 159.
  • 160.
  • 161.
  • 162.
  • 163.
  • 164.
  • 165.
  • 166.
  • 167.
  • 168.
  • 169.
  • 170.
  • 171.
  • 172.
  • 173.
  • 174.
  • 175.
  • 176.
  • 177.
  • 178.
  • 179.
  • 180.
  • 181.
  • 182.
  • 183.
  • 184.
  • 185.
  • 186.
  • 187.
  • 188.
  • 189.
  • 190.
  • 191.
  • 192.
  • 193.
  • 194.
  • 195.
  • 196.
  • 197.
  • 198.
  • 199.
  • 200.
  • 201.
  • 202.
  • 203.
  • 204.
  • 205.
  • 206.
  • 207.
  • 208.
  • 209.
  • 210.
  • 211.
  • 212.
  • 213.
  • 214.
  • 215.
  • 216.
  • 217.
  • 218.
  • 219.
  • 220.
  • 221.
  • 222.
  • 223.
  • 224.
分享
微博
QQ
微信
回复
2024-11-08 17:31:39
相关问题
HarmonyOS http请求大于5M图片报错
614浏览 • 1回复 待解决
HTTP请求传输大于5m文件报错2300023
1243浏览 • 1回复 待解决
HarmonyOS H5调用APP图库选择图片
849浏览 • 1回复 待解决
对指定url图片进行下载保存
2080浏览 • 1回复 待解决
HarmonyOS 如何下载图片
732浏览 • 1回复 待解决
HarmonyOS 如何拉起图库中的指定图片
579浏览 • 1回复 待解决
HarmonyOS 保存网络图片图库更新
1023浏览 • 1回复 待解决
HarmonyOS 图片文件下载
960浏览 • 1回复 待解决
HarmonyOS 保存网络图片到手机图库
610浏览 • 1回复 待解决
HarmonyOS 保存网络图片图库问题
922浏览 • 1回复 待解决
分布式如何读写图库图片或者视频?
5408浏览 • 1回复 待解决
HarmonyOS 图片下载相关
672浏览 • 1回复 待解决
HarmonyOS Web加载Url图片不能显示
1059浏览 • 1回复 待解决