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%')
  }
}
相关推荐
zhanshuo3 小时前
在鸿蒙里优雅地处理网络错误:从 Demo 到实战案例
harmonyos
zhanshuo3 小时前
在鸿蒙中实现深色/浅色模式切换:从原理到可运行 Demo
harmonyos
whysqwhw8 小时前
鸿蒙分布式投屏
harmonyos
whysqwhw9 小时前
鸿蒙AVSession Kit
harmonyos
whysqwhw11 小时前
鸿蒙各种生命周期
harmonyos
whysqwhw12 小时前
鸿蒙音频编码
harmonyos
whysqwhw12 小时前
鸿蒙音频解码
harmonyos
whysqwhw12 小时前
鸿蒙视频解码
harmonyos
whysqwhw12 小时前
鸿蒙视频编码
harmonyos
ajassi200012 小时前
开源 Arkts 鸿蒙应用 开发(十八)通讯--Ble低功耗蓝牙服务器
华为·开源·harmonyos