HarmonyOS Next应用开发——图像PixelMap压缩保存

【高心星出品】

图片编码保存

图片编码指将PixelMap编码成不同格式的存档图片,当前支持打包为JPEG、WebP、png和 HEIF(不同硬件设备支持情况不同) 格式,用于后续处理,如保存、传输等。图片编码是图片解码-图片处理-图片保存的最后环节,保存到当前应用沙箱中比较简单,但保存到用户文件中就比较麻烦。

图片保存到应用沙箱
图片压缩成字节数组
typescript 复制代码
// 图片打包器
let packer=image.createImagePacker()
let file=fileIo.openSync(getContext(this).getApplicationContext().cacheDir+'/edit.jpg',fileIo.OpenMode.CREATE|fileIo.OpenMode.READ_WRITE)
// 将pixelmap打包成字节数组
 packer.packing(this.src,{format:'image/jpeg',quality:100}).then((buffer)=>{
  // 将字节数组 写入文件
  fileIo.writeSync(file.fd,buffer)
 })
图片直接打包成文件
typescript 复制代码
// 图片打包器
let packer=image.createImagePacker()
let file=fileIo.openSync(getContext(this).getApplicationContext().cacheDir+'/edit.jpg',fileIo.OpenMode.CREATE|fileIo.OpenMode.READ_WRITE)
// 直接打包成文件
packer.packToFile(this.src,file.fd,{format:'image/jpeg',quality:100}).then(()=>{
  promptAction.showToast({message:'文件保存成功!'})

}).catch(((e:Error)=>{console.error('gxxt ',e.message)}))
完整代码
typescript 复制代码
import { image } from '@kit.ImageKit';
import { fileIo } from '@kit.CoreFileKit';
import { promptAction } from '@kit.ArkUI';

@Entry
@Component
struct Imgsave {
  @State message: string = 'Hello World';
  @State src:PixelMap|undefined=undefined
  aboutToAppear(): void {
   //  资源管理器
   let rsmanager=getContext(this).resourceManager
   //  图片字节
   let buffer= rsmanager.getMediaContentSync($r('app.media.jingse')).buffer.slice(0)
    // 生成imagesource
    let source=image.createImageSource(buffer)
    // 生成pixelmap
    this.src=source.createPixelMapSync({editable:true})
  }
  savepic(){
    // 图片打包器
    let packer=image.createImagePacker()
    let file=fileIo.openSync(getContext(this).getApplicationContext().cacheDir+'/edit.jpg',fileIo.OpenMode.CREATE|fileIo.OpenMode.READ_WRITE)
    // 将pixelmap打包成字节数组
    // packer.packing(this.src,{format:'image/jpeg',quality:100}).then((buffer)=>{
    //   // 将字节数组 写入文件
    //   fileIo.writeSync(file.fd,buffer)
    // })
    // 直接打包成文件
    packer.packToFile(this.src,file.fd,{format:'image/jpeg',quality:100}).then(()=>{
      promptAction.showToast({message:'文件保存成功!'})

    }).catch(((e:Error)=>{console.error('gxxt ',e.message)}))
  }
  build() {
    Column(){
     Image(this.src).width(300).height(300).objectFit(ImageFit.Fill)
      Button('变换保存').width('60%').margin({top:20})
        .onClick(()=>{
          // 图片透明度改变和图片旋转180
          this.src?.opacitySync(0.5)
          this.src?.rotate(180)
        //   图片保存
          this.savepic()
        })

    }.width('100%')
    .height('100%')
  }
}
图片保存到用户文件

由于用户文件系统与应用文件系统的隔离机制,想要访问用户文件系统,首先需要加入权限ohos.permission.WRITE_IMAGEVIDEO。

但鸿蒙又提供了一种临时获取用户权限的组件SaveButton,使用该组件不用申请权限可以临时获取用户文件系统的访问权限。

保存到相册
typescript 复制代码
 //  图片打包
            let packer = image.createImagePacker()
            packer.packing(this.src, { format: 'image/jpeg', quality: 100 }).then(async (buffer) => {
              //   获取图片的字节数组
              //   获取图库图片操作管理员
              let phhelper = photoAccessHelper.getPhotoAccessHelper(getContext(this))
              // 保存相册请求 参数为上下文环境 保存类型
              let request = photoAccessHelper.MediaAssetChangeRequest.createAssetRequest(getContext(this),
                photoAccessHelper.PhotoType.IMAGE, 'jpg')
              // 将字节数组加入相册资源
              request.addResource(photoAccessHelper.ResourceType.IMAGE_RESOURCE, buffer)
              // 将相册改变保存
              phhelper.applyChanges(request).then(() => {

                promptAction.showToast({ message: '文件保存成功' })
              })
            })
完整代码
typescript 复制代码
import { image } from '@kit.ImageKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { fileIo } from '@kit.CoreFileKit';
import { promptAction } from '@kit.ArkUI';

@Entry
@Component
struct Imagesave1 {
  @State message: string = 'Hello World';
  @State src: PixelMap | undefined = undefined

  aboutToAppear(): void {
    //  资源管理器
    let rsmanager = getContext(this).resourceManager
    //  图片字节
    let buffer = rsmanager.getMediaContentSync($r('app.media.jingse')).buffer.slice(0)
    // 生成imagesource
    let source = image.createImageSource(buffer)
    // 生成pixelmap
    this.src = source.createPixelMapSync({ editable: true })
  }

  build() {
    Column() {
      Image(this.src).width(300).height(300).objectFit(ImageFit.Fill).margin({ bottom: 20 })
      SaveButton({ text: SaveDescription.SAVE_IMAGE }).width('60%')
        .onClick((event: ClickEvent, result: SaveButtonOnClickResult) => {
          if (result == SaveButtonOnClickResult.SUCCESS) {
            //   授权成功
            //   图片水平翻转
            this.src?.flip(true, false)
            //  图片打包
            let packer = image.createImagePacker()
            packer.packing(this.src, { format: 'image/jpeg', quality: 100 }).then(async (buffer) => {
              //   获取图片的字节数组
              //   获取图库图片操作管理员
              let phhelper = photoAccessHelper.getPhotoAccessHelper(getContext(this))
              // 保存相册请求 参数为上下文环境 保存类型
              let request = photoAccessHelper.MediaAssetChangeRequest.createAssetRequest(getContext(this),
                photoAccessHelper.PhotoType.IMAGE, 'jpg')
              // 将字节数组加入相册资源
              request.addResource(photoAccessHelper.ResourceType.IMAGE_RESOURCE, buffer)
              // 将相册改变保存
              phhelper.applyChanges(request).then(() => {

                promptAction.showToast({ message: '文件保存成功' })
              })
            })
          } else {
            promptAction.showToast({ message: '权限申请失败' })
          }
        })

    }.width('100%')
    .height('100%')
  }
}
          })
            })
          } else {
            promptAction.showToast({ message: '权限申请失败' })
          }
        })

    }.width('100%')
    .height('100%')
  }
}
相关推荐
resh_people13 小时前
开源鸿蒙平台 KMP_CMP 三方库「Kermit」适配全流程
华为·开源·harmonyos
李游Leo15 小时前
HarmonyOS 7 EasyGo + ArkUI Navigation:平行视界主副页筛选事务与跨栏撤销一致性【鸿蒙心迹】
华为·harmonyos
HwJack2015 小时前
【共创稿事节】HarmonyOS 7空间应用的可用性测试和体验评估小方法分享
华为·harmonyos·可用性测试
m0_7381858216 小时前
Flutter 鸿蒙化实战:flutter_scankit 适配 OpenHarmony,华为 ScanKit 扫码
flutter·华为·harmonyos·鸿蒙
zhangfeng113316 小时前
Ag / Cu / Au / Ru / Ir / Rh银 铜 金 钌铱 铑 纳米尺度下的 导电性 + 扩散/迁移缺点
人工智能·华为·ai编程·npu
用户1179104883317 小时前
别让AI随便启动你的LSP:hmharness给语言服务器加SHA256门禁 GitHub:swsgbl/hmharness
ai编程·harmonyos
李游Leo21 小时前
HarmonyOS 7 + Share Kit-Window Kit:精准碰一碰屏幕坐标的窗口换算与落点拒绝【鸿蒙心迹】
华为·harmonyos
翼辉cto21 小时前
Compose Multiplatform KV 存储库 multiplatform-settings 的 OpenHarmony 鸿蒙化适配实战
华为·harmonyos
事圆则缓1 天前
Flutter 开发鸿蒙实战:从 OpenHarmony 适配版到 HAP 构建与插件接入
flutter·华为·harmonyos
传奇开心果编程1 天前
【ArkUI进阶练中学】第9课:分布式能力与多设备协同
学习·ui·华为·harmonyos