目录:
1. 组件compress功能介绍
2. 组件compress使用方法
3. 组件compress开发实现

1. 组件compress功能介绍
1.1.  组件介绍:
        compress是一个轻量级图像压缩库。compress允许将大照片压缩成小尺寸的照片,图像质量损失非常小或可以忽略不计。

1.2.  手机模拟器上运行效果:
   

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

2.2.  设置布局

<DependentLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:width="match_parent"
ohos:height="match_parent"
ohos:background_element="#FFFFFF">
<Image
ohos:id="$+id:image1"
ohos:height="match_parent"
ohos:width="match_parent"
ohos:image_src="$media:dog1.PNG"/>
<Text
ohos:id="$+id:text"
ohos:width="match_content"
ohos:height="match_content"
ohos:text=""
ohos:text_size="19fp"
ohos:text_color="#1C1C1C"
ohos:top_padding="8vp"
ohos:bottom_padding="8vp"
ohos:right_padding="70vp"
ohos:left_padding="70vp"
ohos:center_in_parent="true"
ohos:align_parent_bottom="true"
ohos:bottom_margin="120vp"/>
<Button
ohos:id="$+id:choose_button"
ohos:width="match_content"
ohos:height="match_content"
ohos:text="Choose Image"
ohos:text_size="19fp"
ohos:text_color="#FFFFFF"
ohos:top_padding="8vp"
ohos:bottom_padding="8vp"
ohos:right_padding="70vp"
ohos:left_padding="70vp"
ohos:background_element="$graphic:background_button"
ohos:center_in_parent="true"
ohos:align_parent_bottom="true"
ohos:bottom_margin="75vp"/>
<Button
ohos:id="$+id:button"
ohos:width="match_content"
ohos:height="match_content"
ohos:text="Compress"
ohos:text_size="19fp"
ohos:text_color="#FFFFFF"
ohos:top_padding="8vp"
ohos:bottom_padding="8vp"
ohos:right_padding="70vp"
ohos:left_padding="70vp"
ohos:background_element="$graphic:background_button"
ohos:center_in_parent="true"
ohos:align_parent_bottom="true"
ohos:bottom_margin="15vp"/>
</DependentLayout>

2.3.  图像压缩
核心类:Compressor

核心方法:

(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)默认压缩:

public static File defaultCompress(Context context, File file) throws IOException

参数:

context - 应用程序上下文

file - 待压缩图片抽象路径名

结果:

返回压缩后图片抽象路径名。

异常:

发生I/O异常

简单示例:

运行示例前需要在模拟器保存一张截图或使用相机功能照一张照片

public void onStart(Intent intent) {

    super.onStart(intent);

    super.setUIContent(ResourceTable.Layout_ability_main);

    // 请求文件的读取权限

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

    requestPermissionsFromUser(permissions, 0);

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

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

    if (button != null) {

        // 为按钮设置点击回调

        button.setClickedListener(new Component.ClickedListener() {

            @Override

            public void onClick(Component component) {

                try {

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

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

                    // 默认压缩

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

                    // 自定义压缩

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

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

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

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

                    PixelMap newPixelMap = Compressor.decode(newFile);

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

                    image.setPixelMap(newPixelMap);

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

        });

    }

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

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

    if (chooseButton != null) {

        // 为按钮设置点击回调

        chooseButton.setClickedListener(new Component.ClickedListener() {

            @Override

            public void onClick(Component component) {

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

                try {

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

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

                        // 互殴媒体库的图片

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

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

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

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

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

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

                        decodingOpts.sampleSize = ImageSource.DecodingOptions.DEFAULT_SAMPLE_SIZE;

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

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

                        ImagePacker imagePacker = ImagePacker.create();

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

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

                        FileOutputStream outputStream = new FileOutputStream(file);

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

                        packingOptions.quality = 100;

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

                        result = imagePacker.addImage(pixelMap);

                        long dataSize = imagePacker.finalizePacking();

                        // 显示图片和图片大小

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

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

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

                        image.setPixelMap(pixelMap);

                    }

                } catch (DataAbilityRemoteException | FileNotFoundException e) {

                    e.printStackTrace();

                }

            }

        });

    }

}

3. 组件compress开发实现
3.1.  拷贝图片制临时目录
传入的图片路径拷贝临时文件到应用的临时目录。

private static File copyToCache(Context context, File imageFile) throws IOException {

    PixelMap pixelMap = decode(imageFile);

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

    File cacheFile = new File(cachePath);

    int quality = 100; // 压缩质量

    refreshTmpFile(pixelMap, cacheFile, quality);

    return cacheFile;

}

3.2.  图片解码
对临时目录里的图片进行解码

private static PixelMap decode(File file, int width, int height) {

    ImageSource imageSource = ImageSource.create(file, null);
mageSource.DecodingOptions decodingOpts = new ImageSource.DecodingOptions();
decodingOpts.desiredSize = new Size(width, height);
return imageSource.createPixelmap(decodingOpts); }

3.3.  图片编码
按照开发人员设定的规则进行编码,生成新图片

private static void refreshTmpFile(PixelMap pixelMap, File file, int quality)

throws IOException {

    ImagePacker imagePacker = ImagePacker.create();

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

    options.quality = quality;

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

    imagePacker.addImage(pixelMap);

    imagePacker.finalizePacking();

}

项目源代码地址:https://github.com/isoftstone-dev/Compressor_Harmony

作者:软通田可辉

想了解更多内容,请访问: 51CTO和华为官方战略合作共建的鸿蒙技术社区https://harmonyos.51cto.com

HarmonyOS三方件开发指南(7)——compress组件的更多相关文章

  1. HarmonyOS三方件开发指南(14)-Glide组件功能介绍

    <HarmonyOS三方件开发指南>系列文章合集 引言 在实际应用开发中,会用到大量图片处理,如:网络图片.本地图片.应用资源.二进制流.Uri对象等,虽然官方提供了PixelMap进行图 ...

  2. HarmonyOS三方件开发指南(19)-BGABadgeView徽章组件

    目录: 1.引言 2.功能介绍 3.BGABadgeView 使用指南 4.BGABadgeView 开发指南 5.<HarmonyOS三方件开发指南>系列文章合集 引言 现在很多的APP ...

  3. HarmonyOS三方件开发指南(12)——cropper图片裁剪

    鸿蒙入门指南,小白速来!0基础学习路线分享,高效学习方法,重点答疑解惑--->[课程入口] 目录:1. cropper组件功能介绍2. cropper使用方法3. cropper组件开发实现4. ...

  4. HarmonyOS三方件开发指南(13)-SwipeLayout侧滑删除

    鸿蒙入门指南,小白速来!0基础学习路线分享,高效学习方法,重点答疑解惑--->[课程入口] 目录:1. SwipeLayout组件功能介绍2. SwipeLayout使用方法3. SwipeLa ...

  5. HarmonyOS三方件开发指南(15)-LoadingView功能介绍

    目录: 1. LoadingView组件功能介绍2. Lottie使用方法3. Lottie开发实现4.<HarmonyOS三方件开发指南>系列文章合集 1. LoadingView组件功 ...

  6. HarmonyOS三方件开发指南(16)-VideoCache 视频缓存

    目录: 1.引言 2.功能介绍 3.VideoCache使用指南 4.VideoCache开发指南 5.<HarmonyOS三方件开发指南>系列文章合集 引言 对于视频播放器这个app大家 ...

  7. HarmonyOS三方件开发指南(17)-BottomNavigationBar

    目录: 1.引言 2.功能介绍 3.BottomNavigationBar使用指南 4.BottomNavigationBar开发指南 5.<HarmonyOS三方件开发指南>文章合集 引 ...

  8. HarmonyOS三方件开发指南(8)——RoundedImage

    [小年答谢,新春送礼]免费抽取1000元京东卡+更多新春好礼~查看详情>>> 目录: 1. RoundedImage组件功能介绍 2. RoundedImage使用方法 3. Rou ...

  9. HarmonyOS三方件开发指南(4)——Logger组件

    目录: 1.      Logger功能介绍 2.      Logger使用方法 3.      Logger开发实现 4.      源码上传地址 1.      Logger功能介绍1.1.   ...

随机推荐

  1. JAVA基础之接口

    接口 学习完框架之后,整合SSM过程中对于接口的认识加深了许多.根据<java核心技术>这本书进一步研究了一下. 1.概念 java核心技术是这样说的:"在Java程序设计中,接 ...

  2. 第三章节 BJROBOT 角速度校正 【ROS全开源阿克曼转向智能网联无人驾驶车】

    1.把小车平放在地板上,用资料里的虚拟机,打开一个终端 ssh 过去主控端启动roslaunch znjrobot bringup.launch .   2.再打开一个终端 ssh 过去主控端,启动校 ...

  3. CSS系列 (05):浮动详解

    浮动的框可以向左或向右移动,直到它的外边缘碰到包含框或另一个浮动框的边框为止.由于浮动框不在文档的普通流中,所以文档的普通流中的块框表现得就像浮动框不存在一样. -- W3C 文字环绕 float可以 ...

  4. JavaScript基础知识梳理

    一.简单数据类型 Number.String.Boolean.Undefined.Null 1.Number: 方法: toPrecision( ) 返回指定长度的数字(范围是1到100) toFix ...

  5. 使用Python实现的4种快速排序算法

    快速排序算法,总体来说就是选一个基准值,把小于基准值的分一拨,把大于基准值的分到另一拨,然后递归. 有区别的是,分区算法有差异,最直接的是,选个基准值,定义两个列表(小值分区less和大值分区grea ...

  6. TensorFlow 基础概念

    初识TensorFlow,看了几天教程后有些无聊,决定写些东西,来夯实一下基础,提供些前进动力. 一.Session.run()和Tensor.eval()的区别: 最主要的区别就是可以使用sess. ...

  7. idea多模块启动

    2018版本的idea 原文链接http://zhhll.icu/2020/04/07/idea/idea%E4%B9%8B%E5%A4%9A%E6%A8%A1%E5%9D%97%E5%90%AF%E ...

  8. Java 使用拦截器无限转发/重定向无限循环/重定向次数过多报错(StackOverflowError) 解决方案

    说明:当使用拦截器出现"请求转发"无限循环或者"重定向"次数过多这种问题的时候,一般都是 拦截器 设置错了 情况一:请求转发时没有配置排除拦截路径,就是说你访问 ...

  9. CODING x 腾讯兔小巢,打破研发团队与用户反馈的最后一道壁垒

    任何产品的更新迭代都离不开用户的使用反馈.产品经理日常需要奔走到一线部门了解用户的使用反馈:一线运营或业务团队日常需要向产品经理转述用户的问题场景及催促需求的进度.中间需要消耗大量的精力来进行信息转达 ...

  10. 【Linux】zabbix4.0服务器搭建,agent搭建,及邮件使用方法

    zabbix默认的 服务端监听端口为10051,而被监控端即Zabbix--agents代理程序监控10050端口. 更新yum源: yum clean all yum makecache 需要配置网 ...