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

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

HarmonyOS
10h前
浏览
收藏 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 
};

以下是完整的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') 
  } 
}
分享
微博
QQ
微信
回复
2h前
相关问题
HTTP请求传输大于5m文件报错2300023
304浏览 • 1回复 待解决
对指定url图片进行下载保存
888浏览 • 1回复 待解决
HarmonyOS 保存网络图片图库更新
117浏览 • 1回复 待解决
分布式如何读写图库图片或者视频?
4439浏览 • 1回复 待解决
HarmonyOS关于下载到缓存目录的问题
328浏览 • 1回复 待解决
把应用沙箱下的图片保存到图库
942浏览 • 1回复 待解决
HarmonyOS H5如何访问相册?
28浏览 • 1回复 待解决
image组件是否支持图片下载链接
1554浏览 • 1回复 待解决