HarmonyOS 使用imagePackerApi.packToFile压缩图片报错

HarmonyOS
2天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
FengTianYa

麻烦参照以下demo检查下相关参数,示例如下:

import { common } from '@kit.AbilityKit';
import { BusinessError, request } from '@kit.BasicServicesKit';
import fs from '@ohos.file.fs';
import { fileUri } from '@kit.CoreFileKit';
import { joinPicture } from '../../utils/JoinPicture'
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { image } from '@kit.ImageKit';

@Entry
@Component
struct Index {
  @State imageUri: string = '';
  @State combineImageUri: string = '';
  context = getContext(this) as common.UIAbilityContext;
  filePath = this.context.filesDir + '/test.jpg';
  combinePath = this.context.filesDir + '/combine.jpg';
  saveButtonOptions: SaveButtonOptions = {
    icon: SaveIconStyle.FULL_FILLED,
    text: SaveDescription.SAVE_IMAGE,
    buttonType: ButtonType.Capsule
  } // 设置安全控件按钮属性
  onPageShow(): void {
    this.checkImageExist()
  }

  checkImageExist(notExistCallback?: Function) {
    fs.access(this.filePath).then((res: boolean) => {
      if (res) {
        console.info("PictureJoinTogether file exists");
        this.imageUri = fileUri.getUriFromPath(this.filePath);
      } else {
        console.info("PictureJoinTogether file not exists");
        if (notExistCallback) {
          notExistCallback()
        }
      }
    }).catch((err: BusinessError) => {
      console.info("PictureJoinTogether access failed with error message: " + err.message + ", error code: " + err.code);
    });
  }

  // 只是为了分享图片,随便找个图片下载
  downloadFile(callback: Function) {
    this.checkImageExist(() => {
      request.downloadFile(this.context, {
        url: 'xxxx',
        filePath: this.filePath,
        background: true
      }).then((downloadTask: request.DownloadTask) => {
        downloadTask.on('progress', (receivedSize: number, totalSize: number) => {
          console.info("PictureJoinTogether download receivedSize:" + receivedSize + " totalSize:" + totalSize);
        });
        downloadTask.on('complete', () => {
          console.info('PictureJoinTogether download complete');
          callback()
        })
      }).catch((err: BusinessError) => {
        console.error(`PictureJoinTogether Invoke downloadTask failed, code is ${err.code}, message is ${err.message}`);
      });
    })
  }

  build() {
    Column({space: 10}) {
      Button('下载图片')
        .onClick(() => {
          if (this.imageUri !== '') {
            return;
          }
          this.downloadFile(() => {
            this.imageUri = fileUri.getUriFromPath(this.filePath);
          })
        })

      Image(this.imageUri)
        .width(200)
        .height(200)
        .backgroundColor(Color.Gray)

      Button('合并图片并保存到应用内')
        .onClick(() => {
          joinPicture.join([this.filePath, this.filePath], this.combinePath, () => {
            this.combineImageUri = fileUri.getUriFromPath(this.combinePath);
          })
        })

      Image(this.combineImageUri)
        .width(400)
        .height(200)
        .backgroundColor(Color.Gray)

      // 通过安全控件保存应用图片到图库
      SaveButton(this.saveButtonOptions)
        .onClick(async (event, result: SaveButtonOnClickResult) => {
          if (result === SaveButtonOnClickResult.SUCCESS) {
            try {
              const context = getContext();
              const phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
              const uri = await phAccessHelper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpg');
              console.info('createAsset successfully, uri: ' + uri);
              const file = await fs.open(uri, fs.OpenMode.READ_WRITE);
              const imageSource = image.createImageSource(this.combinePath);
              const imageInfo = await imageSource.getImageInfo();
              const opts: image.DecodingOptions = {
                editable: true,
                // 注意和拼接图片时的格式统一
                desiredPixelFormat: image.PixelMapFormat.BGRA_8888,
                //desiredPixelFormat: image.PixelMapFormat.RGBA_8888,
                desiredSize: { width: imageInfo.size.width, height: imageInfo.size.height }
              };
              // 需要通过packing打包图片,直接获取buffer并写入会导致图库中图片无法显示
              const pixelMap = await imageSource.createPixelMap(opts);
              const context2 = getContext(this);
              const imageSourceApi: image.ImageSource = image.createImageSource(this.combinePath);
              let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 };
              const filePath: string = context2.filesDir + "/image_source2.jpg";
              let file2 = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
              const imagePackerApi: image.ImagePacker = image.createImagePacker();
              imagePackerApi.packToFile(imageSourceApi, file2.fd, packOpts, (err: BusinessError) => {
                if (err) {
                  console.error(`Failed to pack the image to file.code ${err.code},message is ${err.message}`);
                } else {
                  console.info('Succeeded in packing the image to file.');
                }
              })
            } catch (err) {
              console.error('createAsset failed, message = ', err);
            }
          } else {
            console.error('SaveButtonOnClickResult createAsset failed');
          }
        })
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}
分享
微博
QQ
微信
回复
2天前
相关问题
HarmonyOS 如何压缩图片之后再上传?
57浏览 • 1回复 待解决
HarmonyOS 相册选择后压缩图片大小
6浏览 • 1回复 待解决
API 9 ETS如何进行压缩图片
394浏览 • 1回复 待解决
使用图片压缩API的参数影响
547浏览 • 1回复 待解决
HarmonyOS 图片压缩问题
73浏览 • 1回复 待解决
HarmonyOS 图片压缩失败
4浏览 • 0回复 待解决
HarmonyOS 图片压缩工具
42浏览 • 1回复 待解决
HarmonyOS图片压缩不到指定大小
653浏览 • 1回复 待解决
HarmonyOS 图片压缩图片转base64
342浏览 • 1回复 待解决
HarmonyOS 图片的加载与压缩服务
201浏览 • 1回复 待解决
HarmonyOS 怎么对图片进行压缩上传
86浏览 • 1回复 待解决
flutter适配HarmonyOS图片压缩的库
226浏览 • 1回复 待解决
HarmonyOS 图片的加载与压缩服务?
243浏览 • 0回复 待解决
网络请求:gzip压缩使用
441浏览 • 1回复 待解决