[文章]【软通动力】HarmonyOS三方件开发指南(7)——compress组件

阅读量0
0
4
`1. 组件compress功能介绍
1.1.  组件介绍:
        compress是一个轻量级图像压缩库。compress允许将大照片压缩成小尺寸的照片,图像质量损失非常小或可以忽略不计。
1.2.  手机模拟器上运行效果:
2.png

2. 组件compress使用方法
2.1.  添加依赖
        将compress-debug.har复制到应用的entrylibs目录下即可(由于build.gradle中已经依赖的libs目录下的*.har,因此不需要再做修改)。

2.2.  设置布局
  1. <DependentLayout
  2.     xmlns:ohos="http://schemas.huawei.com/res/ohos"
  3.     ohos:width="match_parent"
  4.     ohos:height="match_parent"
  5.     ohos:background_element="#FFFFFF">
  6.     <Image
  7.         ohos:id="$+id:image1"
  8.         ohos:height="match_parent"
  9.         ohos:width="match_parent"
  10.         ohos:image_src="$media:dog1.PNG"/>
  11.     <Text
  12.         ohos:id="$+id:text"
  13.         ohos:width="match_content"
  14.         ohos:height="match_content"
  15.         ohos:text=""
  16.         ohos:text_size="19fp"
  17.         ohos:text_color="#1C1C1C"
  18.         ohos:top_padding="8vp"
  19.         ohos:bottom_padding="8vp"
  20.         ohos:right_padding="70vp"
  21.         ohos:left_padding="70vp"
  22.         ohos:center_in_parent="true"
  23.         ohos:align_parent_bottom="true"
  24.         ohos:bottom_margin="120vp"/>
  25.     <Button
  26.         ohos:id="$+id:choose_button"
  27.         ohos:width="match_content"
  28.         ohos:height="match_content"
  29.         ohos:text="Choose Image"
  30.         ohos:text_size="19fp"
  31.         ohos:text_color="#FFFFFF"
  32.         ohos:top_padding="8vp"
  33.         ohos:bottom_padding="8vp"
  34.         ohos:right_padding="70vp"
  35.         ohos:left_padding="70vp"
  36.         ohos:background_element="$graphic:background_button"
  37.         ohos:center_in_parent="true"
  38.         ohos:align_parent_bottom="true"
  39.         ohos:bottom_margin="75vp"/>
  40.     <Button
  41.         ohos:id="$+id:button"
  42.         ohos:width="match_content"
  43.         ohos:height="match_content"
  44.         ohos:text="Compress"
  45.         ohos:text_size="19fp"
  46.         ohos:text_color="#FFFFFF"
  47.         ohos:top_padding="8vp"
  48.         ohos:bottom_padding="8vp"
  49.         ohos:right_padding="70vp"
  50.         ohos:left_padding="70vp"
  51.         ohos:background_element="$graphic:background_button"
  52.         ohos:center_in_parent="true"
  53.         ohos:align_parent_bottom="true"
  54.         ohos:bottom_margin="15vp"/>
  55. </DependentLayout>
复制代码
2.3.  图像压缩
核心类:Compressor
核心方法:

(1)自定义压缩:
  1. public static File customCompress(Context context, File file, int width, int height, int quality) throws IOException
复制代码
参数:
context - 应用程序上下文
file - 待压缩图片抽象路径名
width - 压缩后宽度
height - 压缩后高度
quality - 图片压缩质量,范围0~100
结果:
返回压缩后图片抽象路径名。
异常:
发生I/O异常

(2)默认压缩:
  1. public static File defaultCompress(Context context, File file) throws IOException
复制代码
参数:
context - 应用程序上下文
file - 待压缩图片抽象路径名
结果:
返回压缩后图片抽象路径名。
异常:
发生I/O异常
简单示例:

运行示例前需要在模拟器保存一张截图或使用相机功能照一张照片
  1. public void onStart(Intent intent) {

  2.     super.onStart(intent);

  3.     super.setUIContent(ResourceTable.Layout_ability_main);



  4.     // 请求文件的读取权限

  5.     String[] permissions = {"ohos.permission.READ_USER_STORAGE"};

  6.     requestPermissionsFromUser(permissions, 0);



  7.     // 获取压缩按钮并绑定事件

  8.     Button button = (Button) findComponentById(ResourceTable.Id_button);

  9.     if (button != null) {

  10.         // 为按钮设置点击回调

  11.         button.setClickedListener(new Component.ClickedListener() {

  12.             @Override

  13.             public void onClick(Component component) {

  14.                 try {

  15.                     File file = new File(System.getProperty("java.io.tmpdir") + File.separator + tmpName);

  16.                     HiLog.error(LOG_LABEL, "old size..." + file.length() +  " ...b");



  17.                     // 默认压缩

  18.                     // File newFile = Compressor.defaultCompress(file);



  19.                     // 自定义压缩

  20.                     File newFile = Compressor.customCompress(getContext(), file, 500, 1000, 60);

  21.                     Text text = (Text) findComponentById(ResourceTable.Id_text);

  22.                     text.setText("size: " + newFile.length() + " b");

  23.                     HiLog.error(LOG_LABEL, "new size..." + newFile.length() +  " ...b");

  24.                     PixelMap newPixelMap = Compressor.decode(newFile);

  25.                     Image image = (Image) findComponentById(ResourceTable.Id_image1);

  26.                     image.setPixelMap(newPixelMap);

  27.                 } catch (IOException e) {

  28.                     e.printStackTrace();

  29.                 }

  30.             }

  31.         });

  32.     }

  33.     // 获取选择图片按钮并绑定事件

  34.     Button chooseButton = (Button) findComponentById(ResourceTable.Id_choose_button);

  35.     if (chooseButton != null) {

  36.         // 为按钮设置点击回调

  37.         chooseButton.setClickedListener(new Component.ClickedListener() {

  38.             @Override

  39.             public void onClick(Component component) {

  40.                 DataAbilityHelper helper = DataAbilityHelper.creator(getContext());

  41.                 try {

  42.                     ResultSet resultSet = helper.query(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, null, null);

  43.                     while (resultSet != null && resultSet.goToNextRow()) {

  44.                         // 互殴媒体库的图片

  45.                         int id = resultSet.getInt(resultSet.getColumnIndexForName(AVStorage.Images.Media.ID));

  46.                         HiLog.error(LOG_LABEL, "id:..." + id +  " ...");

  47.                         Uri uri = Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, "" + id);

  48.                         // 根据图片的uri打开文件并保存到临时目录中

  49.                         FileDescriptor fileDescriptor = helper.openFile(uri, "r");

  50.                         ImageSource.DecodingOptions decodingOpts = new ImageSource.DecodingOptions();

  51.                         decodingOpts.sampleSize = ImageSource.DecodingOptions.DEFAULT_SAMPLE_SIZE;

  52.                         ImageSource imageSource = ImageSource.create(fileDescriptor, null);

  53.                         PixelMap pixelMap = imageSource.createThumbnailPixelmap(decodingOpts, true);

  54.                         ImagePacker imagePacker = ImagePacker.create();

  55.                         tmpName = UUID.randomUUID().toString();

  56.                         File file = new File(System.getProperty("java.io.tmpdir") + File.separator + tmpName);

  57.                         FileOutputStream outputStream = new FileOutputStream(file);

  58.                         ImagePacker.PackingOptions packingOptions = new ImagePacker.PackingOptions();

  59.                         packingOptions.quality = 100;

  60.                         boolean result = imagePacker.initializePacking(outputStream, packingOptions);

  61.                         result = imagePacker.addImage(pixelMap);

  62.                         long dataSize = imagePacker.finalizePacking();

  63.                         // 显示图片和图片大小

  64.                         Text text = (Text) findComponentById(ResourceTable.Id_text);

  65.                         text.setText("size: " + file.length() + " b");

  66.                         Image image = (Image) findComponentById(ResourceTable.Id_image1);

  67.                         image.setPixelMap(pixelMap);

  68.                     }

  69.                 } catch (DataAbilityRemoteException | FileNotFoundException e) {

  70.                     e.printStackTrace();

  71.                 }

  72.             }

  73.         });

  74.     }

  75. }
复制代码
3. 组件compress开发实现
3.1.  拷贝图片制临时目录
传入的图片路径拷贝临时文件到应用的临时目录。
  1. private static File copyToCache(Context context, File imageFile) throws IOException {

  2.     PixelMap pixelMap = decode(imageFile);

  3.     String cachePath = context.getCacheDir() + File.separator + imageFile.getName();

  4.     File cacheFile = new File(cachePath);

  5.     int quality = 100; // 压缩质量

  6.     refreshTmpFile(pixelMap, cacheFile, quality);

  7.     return cacheFile;

  8. }
复制代码
3.2.  图片解码
对临时目录里的图片进行解码
  1. private static PixelMap decode(File file, int width, int height) {

  2.     ImageSource imageSource = ImageSource.create(file, null);
  3.     mageSource.DecodingOptions decodingOpts = new

  4. ImageSource.DecodingOptions();
  5.     decodingOpts.desiredSize = new Size(width, height);
  6.     return imageSource.createPixelmap(decodingOpts);

  7. }
复制代码
3.3.  图片编码
按照开发人员设定的规则进行编码,生成新图片
  1. private static void refreshTmpFile(PixelMap pixelMap, File file, int quality)

  2. throws IOException {

  3.     ImagePacker imagePacker = ImagePacker.create();

  4.     ImagePacker.PackingOptions options = new ImagePacker.PackingOptions();

  5.     options.quality = quality;

  6.     imagePacker.initializePacking(new FileOutputStream(file), options);

  7.     imagePacker.addImage(pixelMap);

  8.     imagePacker.finalizePacking();

  9. }
复制代码
项目源代码地址:https://github.com/isoftstone-dev/Compressor_Harmony
©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任

`
1.png

回帖

声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容图片侵权或者其他问题,请联系本站作侵删。 侵权投诉
链接复制成功,分享给好友