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%')
  }
}
相关推荐
二二孚日1 小时前
自用华为ICT云赛道AI第三章知识点-MindSpore特性、MindSpore开发组件
人工智能·华为
Georgewu2 小时前
【HarmonyOS 5】鸿蒙中自定义弹框OpenCustomDialog、CustomDialog与DialogHub的区别详解
harmonyos
塞尔维亚大汉2 小时前
鸿蒙内核源码分析(消息封装篇) | 剖析LiteIpc 进程通讯内容
harmonyos·源码阅读
Georgewu2 小时前
【HarmonyOS NEXT】鸿蒙跳转华为应用市场目标APP下载页
harmonyos
ajassi20004 小时前
开源 Arkts 鸿蒙应用 开发(六)数据持久--文件和首选项存储
linux·开源·harmonyos
塞尔维亚大汉4 小时前
鸿蒙内核源码分析(共享内存) | 进程间最快通讯方式
harmonyos·源码阅读
生如夏花℡8 小时前
HarmonyOS学习记录4
学习·华为·harmonyos
九章云极AladdinEdu8 小时前
华为昇腾NPU与NVIDIA CUDA生态兼容层开发实录:手写算子自动转换工具链(AST级代码迁移方案)
人工智能·深度学习·opencv·机器学习·华为·数据挖掘·gpu算力
xq95278 小时前
编程之路2025年中总结,勇往直前 再战江湖
harmonyos
枫叶丹49 小时前
【HarmonyOS Next之旅】DevEco Studio使用指南(四十二) -> 动态修改编译配置
华为·harmonyos·deveco studio·harmonyos next