当前位置:首页 » 程序代码 » 正文

SaveButton组件 ,保存图片到图库,arkts

用 SaveButton 组件来保存一个图片,代码如下:

//SaveButton组件 ,保存图片到图库
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { fileIo } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';
import { promptAction} from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';

const context: Context = getContext(this);

//保存图件的函数
async function savePhotoToGallery(context: common.UIAbilityContext, image1: Resource) {
  let helper = photoAccessHelper.getPhotoAccessHelper(context);
  try {
    // onClick触发后10秒内通过createAsset接口创建图片文件,10秒后createAsset权限收回。
    let uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpg');
    // 使用uri打开文件,可以持续写入内容,写入过程不受时间限制
    let file = await fileIo.open(uri, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
    // $r('app.media.startIcon')需要替换为开发者所需的图像资源文件
    context.resourceManager.getMediaContent(image1.id, 0)
      .then(async value => {
        let media = value.buffer;
        // 写到媒体库文件中
        await fileIo.write(file.fd, media);
        await fileIo.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}`);
  }
}


@Entry
@Component
struct Page6 {

  img: Resource = $r('app.media.jj930') //先准备好一张图片,源码来自 wb98.com

  build() {
    Row() {
      Column({ space: 10 }) {

        Image(this.img)
          .height(400)
          .width('100%')

        SaveButton({icon:SaveIconStyle.FULL_FILLED,text:SaveDescription.SAVE_IMAGE})  //选项不同,就有不同的按钮文字表述。
          .onClick(async (event: ClickEvent, result: SaveButtonOnClickResult) => {
            if (result === SaveButtonOnClickResult.SUCCESS) {
              const context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
              // 免去权限申请和权限请求等环节,获得临时授权,保存对应图片
              savePhotoToGallery(context, this.img); //调用函数来保存 this.img 图片
            } else {
              promptAction.showToast({ message: '设置权限失败!' })
            }
          })
      }
      .width('100%')
    }
    .height('100%')

  }
}

//C:\Users\DELL\source\repos


打赏 支付宝打赏 微信打赏

来源:济亨网

本文链接:https://www.wb98.com/post/376.html

arkts  鸿蒙  
    << 上一篇 下一篇 >>

    湘公网安备 43011102000514号 - 湘ICP备08100508号