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 小时前
HarmonyOS 小游戏《对战五子棋》开发第2篇-AppScope与entry模块
华为·harmonyos
●VON1 小时前
HarmonyKit | 鸿蒙新特性对比:Tabs vs HdsTabs 选型深度解析
华为·harmonyos·鸿蒙·新特性
binbin_521 小时前
React Native 鸿蒙环境搭建完整实战:从 RN 工程到 RNOH 运行
深度学习·react native·react.js·harmonyos
最爱老式锅包肉2 小时前
《HarmonyOS技术精讲-Core Speech Kit(基础语音服务)》第1篇:音频管理基础与语音服务入门
华为·音视频·harmonyos
最爱老式锅包肉2 小时前
HarmonyOS技术精讲-Speech Kit(场景化语音服务):AI字幕控件赋能实时语音识别与显示
语音识别·harmonyos
千逐682 小时前
Uniapp 鸿蒙实战之 AtomGit APP - 首页设计与仓库列表实现
华为·uni-app·harmonyos
binbin_522 小时前
Flutter 调用鸿蒙原生组件:MethodChannel 与 PlatformView 的选择和落地
开发语言·深度学习·flutter·harmonyos
云卷云舒___________2 小时前
Gemini 3.5 Pro或17日发布、Grok Imagine新增15秒视频生成、GPT-5.6 Sol 跑30小时超Opus | 7月5日 AI日报
华为·ai·grok·视频生成·gemini·ai日报·gpt56
●VON2 小时前
HarmonyKit | 鸿蒙新特性规范:10 个工具页 UI 一致性设计系统
ui·华为·harmonyos·鸿蒙·新特性
木木子2213 小时前
# 待办事项应用深度解析:ForEach 列表渲染与 CRUD 操作实战
windows·华为·harmonyos