chenjun3_wd

图片下载模块

  1 +import { abilityAccessCtrl, common, Permissions } from '@kit.AbilityKit';
  2 +import { http } from '@kit.NetworkKit';
  3 +import { BusinessError } from '@kit.BasicServicesKit';
  4 +import { promptAction } from '@kit.ArkUI';
  5 +import { image } from '@kit.ImageKit';
  6 +import { photoAccessHelper } from '@kit.MediaLibraryKit';
  7 +import fs from '@ohos.file.fs';
  8 +
  9 +const PERMISSIONS: Array<Permissions> = [
  10 + 'ohos.permission.READ_MEDIA',
  11 + 'ohos.permission.WRITE_MEDIA'
  12 +];
  13 +
  14 +@Component
  15 +export struct ImageDownloadComponent {
  16 + @State image: PixelMap | undefined = undefined;
  17 + @State photoAccessHelper: photoAccessHelper.PhotoAccessHelper | undefined = undefined; // 相册模块管理实例
  18 + @State imageBuffer: ArrayBuffer | undefined = undefined; // 图片ArrayBuffer
  19 + url: string = ''
  20 +
  21 + build() {
  22 + Column() {
  23 + Image($r('app.media.icon_arrow_left_white'))
  24 + .width(24)
  25 + .height(24)
  26 + .aspectRatio(1)
  27 + .interpolation(ImageInterpolation.High)
  28 + .rotate({ angle: -90 })
  29 + .onClick(async () => {
  30 + console.info(`cj2024 onClick ${this.imageBuffer}`)
  31 + if (this.imageBuffer !== undefined) {
  32 + await this.saveImage(this.imageBuffer);
  33 + promptAction.showToast({
  34 + message: $r('app.string.image_request_success'),
  35 + duration: 2000
  36 + })
  37 + }
  38 + })
  39 + }
  40 +
  41 + }
  42 +
  43 + async aboutToAppear(): Promise<void> {
  44 + console.info(`cj2024 图片下载 ${this.url}`)
  45 + const context = getContext(this) as common.UIAbilityContext;
  46 + const atManager = abilityAccessCtrl.createAtManager();
  47 + await atManager.requestPermissionsFromUser(context, PERMISSIONS);
  48 + this.getPicture();
  49 + }
  50 +
  51 + /**
  52 + * 通过http的request方法从网络下载图片资源
  53 + */
  54 + async getPicture() {
  55 + console.info(`cj2024 getPicture`)
  56 + http.createHttp()
  57 + .request(this.url,
  58 + (error: BusinessError, data: http.HttpResponse) => {
  59 + if (error) {
  60 + // 下载失败时弹窗提示检查网络,不执行后续逻辑
  61 + promptAction.showToast({
  62 + message: $r('app.string.image_request_fail'),
  63 + duration: 2000
  64 + })
  65 + return;
  66 + }
  67 + this.transcodePixelMap(data);
  68 + // 判断网络获取到的资源是否为ArrayBuffer类型
  69 + console.info(`cj2024 getPicture ${data.result}`)
  70 + if (data.result instanceof ArrayBuffer) {
  71 + console.info(`cj2024 getPicture 222`)
  72 + this.imageBuffer = data.result as ArrayBuffer;
  73 + }
  74 + }
  75 + )
  76 + }
  77 +
  78 + /**
  79 + * 使用createPixelMap将ArrayBuffer类型的图片装换为PixelMap类型
  80 + * @param data:网络获取到的资源
  81 + */
  82 + transcodePixelMap(data: http.HttpResponse) {
  83 + console.info(`cj2024 transcodePixelMap ${data.responseCode}`)
  84 + if (http.ResponseCode.OK === data.responseCode) {
  85 + const imageData: ArrayBuffer = data.result as ArrayBuffer;
  86 + // 通过ArrayBuffer创建图片源实例。
  87 + const imageSource: image.ImageSource = image.createImageSource(imageData);
  88 + const options: image.InitializationOptions = {
  89 + 'alphaType': 0, // 透明度
  90 + 'editable': false, // 是否可编辑
  91 + 'pixelFormat': 3, // 像素格式
  92 + 'scaleMode': 1, // 缩略值
  93 + 'size': { height: 100, width: 100 }
  94 + }; // 创建图片大小
  95 +
  96 + // 通过属性创建PixelMap
  97 + imageSource.createPixelMap(options).then((pixelMap: PixelMap) => {
  98 + this.image = pixelMap;
  99 + });
  100 + }
  101 + }
  102 +
  103 + /**
  104 + * 保存ArrayBuffer到图库
  105 + * @param buffer:图片ArrayBuffer
  106 + * @returns
  107 + */
  108 + async saveImage(buffer: ArrayBuffer | string): Promise<void> {
  109 + console.info(`cj2024 saveImage buffer ${buffer}`)
  110 + const context = getContext(this) as common.UIAbilityContext; // 获取getPhotoAccessHelper需要的context
  111 + const helper = photoAccessHelper.getPhotoAccessHelper(context); // 获取相册管理模块的实例
  112 + const uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpg'); // 指定待创建的文件类型、后缀和创建选项,创建图片或视频资源
  113 + console.info(`cj2024 saveImage uri ${uri}`)
  114 + const file = await fs.open(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
  115 + await fs.write(file.fd, buffer);
  116 + await fs.close(file.fd);
  117 + }
  118 +}
1 import { PhotoListBean } from 'wdBean/Index'; 1 import { PhotoListBean } from 'wdBean/Index';
2 import { Logger } from 'wdKit/Index'; 2 import { Logger } from 'wdKit/Index';
3 import { MultiPictureDetailItemComponent } from './MultiPictureDetailItemComponent'; 3 import { MultiPictureDetailItemComponent } from './MultiPictureDetailItemComponent';
4 -import { display } from '@kit.ArkUI'; 4 +import { display, router } from '@kit.ArkUI';
  5 +import { ImageDownloadComponent } from './ImageDownloadComponent';
5 6
6 const TAG = 'ImageSwiperComponent'; 7 const TAG = 'ImageSwiperComponent';
7 8
@@ -35,6 +36,20 @@ export struct ImageSwiperComponent { @@ -35,6 +36,20 @@ export struct ImageSwiperComponent {
35 36
36 build() { 37 build() {
37 RelativeContainer() { 38 RelativeContainer() {
  39 + Image($r('app.media.icon_arrow_left_white'))
  40 + .width(24)
  41 + .height(24)
  42 + .aspectRatio(1)
  43 + .interpolation(ImageInterpolation.High)
  44 + .alignRules({
  45 + top: { anchor: "__container__", align: VerticalAlign.Top },
  46 + left: { anchor: "__container__", align: HorizontalAlign.Start }
  47 + })
  48 + .onClick(() => {
  49 + router.back();
  50 + })
  51 + .id("backImg")
  52 +
38 if (this.photoList && this.photoList?.length > 0) { 53 if (this.photoList && this.photoList?.length > 0) {
39 Swiper(this.swiperController) { 54 Swiper(this.swiperController) {
40 ForEach(this.photoList, (item: PhotoListBean) => { 55 ForEach(this.photoList, (item: PhotoListBean) => {
@@ -96,6 +111,19 @@ export struct ImageSwiperComponent { @@ -96,6 +111,19 @@ export struct ImageSwiperComponent {
96 middle: { anchor: "__container__", align: HorizontalAlign.Center } 111 middle: { anchor: "__container__", align: HorizontalAlign.Center }
97 }) 112 })
98 } 113 }
  114 +
  115 + ImageDownloadComponent({ url: this.photoList[this.swiperIndex].picPath })
  116 + .alignRules({
  117 + bottom: { anchor: "__container__", align: VerticalAlign.Bottom },
  118 + right: { anchor: "__container__", align: HorizontalAlign.End }
  119 + })
  120 + .margin({
  121 + top: 8,
  122 + left: 18,
  123 + bottom: 24,
  124 + right: 18
  125 + })
  126 + .id("downloadImg")
99 } 127 }
100 .width('100%') 128 .width('100%')
101 .height('100%') 129 .height('100%')