HarmonyOS三方件开发指南(7)——compress组件

Stella981
• 阅读 467

目录:

1. 组件compress功能介绍

2. 组件compress使用方法

3. 组件compress开发实现

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

1.2.  手机模拟器上运行效果:
   HarmonyOS三方件开发指南(7)——compress组件

HarmonyOS三方件开发指南(7)——compress组件

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

【小年答谢,新春送礼】免费抽取1000元京东卡+更多新春好礼~

HarmonyOS三方件开发指南(7)——compress组件

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
11个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
4年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
HarmonyOS三方件开发指南(8)——RoundedImage
目录:1\.RoundedImage组件功能介绍(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fharmonyos.51cto.com%2Fposts%2F3068%23kyzg)2\.RoundedImage使用方法(https://www.oschina.net/a
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Stella981 Stella981
3年前
HarmonyOS三方件开发指南(10)——GifImage
目录:1\.GifImage组件功能介绍(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fharmonyos.51cto.com%2Fposts%2F3183%23kyzg)2\.GifImage使用方法(https://w
Python进阶者 Python进阶者
1年前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这
美凌格栋栋酱 美凌格栋栋酱
4个月前
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(