当前位置:首页 > 未命名 > 正文内容

鸿蒙next保存图片、视频组件

dsttl34个月前 (05-21)未命名462

page

import photoAccessHelper from '@ohos.file.photoAccessHelper';
import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common';
import promptAction from '@ohos.promptAction';
import { BusinessError } from '@ohos.base';

@Entry
@Component
struct Page {

  build() {
    Row() {
      Column({ space: 10 }) {
        Image($r('app.media.icon'))
          .height(400)
          .width('100%')
        SaveButton().onClick(async (event: ClickEvent, result: SaveButtonOnClickResult) => {
          if (result === SaveButtonOnClickResult.SUCCESS) {
            const context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
            // 免去权限申请和权限请求等环节,获得临时授权,保存对应图片
            savePhotoToGallery(context);
          } else {
            promptAction.showToast({ message: '设置权限失败!' })
          }
        })
      }
      .width('100%')
    }
    .height('100%')
    .backgroundColor(0xF1F3F5)
  }
}

async function savePhotoToGallery(context: common.UIAbilityContext) {
  let helper = photoAccessHelper.getPhotoAccessHelper(context);
  try {
    // 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);
    context.resourceManager.getMediaContent($r('app.media.icon').id, 0)
      .then(async value => {
        let media = value.buffer;
        // 写到媒体库文件中
        await fs.write(file.fd, media);
        await fs.close(file.fd);
        promptAction.showToast({ message: '已保存至相册!' });
      });
  }
  catch (error) {
    const err: BusinessError = error as BusinessError;
    console.error(`Failed to save photo. Code is ${err.code}, message is ${err.message}`);
  }
}

权限

      {
        "name": "ohos.permission.WRITE_IMAGEVIDEO",
        "reason": "$string:READ_WRITE_DOWNLOAD",
        "usedScene":  {
          "abilities": ["EntryAbility"],
          "when": "inuse"
        }
      },

扫描二维码推送至手机访问。

版权声明:本文由dsttl3发布,如需转载请注明出处。

本文链接:https://dsttl3.cn/?id=483

分享给朋友: