今日看点

【软通动力】HarmonyOS三方件开发指南(7)

发表于话题:HarmonyOS 2
发布时间:2021-06-02

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

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

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

2.2.  设置布局

2.3.  图像压缩
核心类:Compressor

核心方法:

(1)自定义压缩:

public static File customCompress(Context context, File file, int width, int height, int ) throws IOException

参数:

context - 应用程序上下文

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

width - 压缩后宽度

height - 压缩后高度

- 图片压缩质量,范围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"}; reser(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. = 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 = 100; // 压缩质量 refreshTmpFile(pixelMap, cacheFile, ); 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 ) throws IOException { ImagePacker imagePacker = ImagePacker.create(); ImagePacker.PackingOptions options = new ImagePacker.PackingOptions(); options. = ; imagePacker.initializePacking(new FileOutputStream(file), options); imagePacker.addImage(pixelMap); imagePacker.finalizePacking(); }

 

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

欢迎交流:

 

 

标签组:[context

本文来源:https://www.kandian5.com/articles/23980.html

相关阅读

宋襄公的"仁义":一场春秋时代的道德困境

春秋时期,宋国君主宋襄公以"仁义"之名载入史册,却在泓水之战中因坚持"不鼓不成列"的古礼惨败,成为后世讥讽的"蠢猪式仁义"代表。然而,若将这一事件置于春秋中期的历史语境中审视,宋襄公的"仁义"既非纯粹...

2025-07-09

秦惠文王晚年真的疯了吗?历史与传说的交织

秦惠文王嬴驷(公元前356年—公元前311年)是战国时期秦国历史上极具争议的君主。他以“车裂商鞅”开启政治生涯,以“称王改制”奠定霸业根基,又以“连横破纵”的外交谋略将秦国推向强盛。然而,这位在位仅2...

2025-07-09

白起若置身三国:战神之姿能否续写不败传奇?

在中国冷兵器战争史上,白起以“人屠”之名成为战国军事的巅峰符号。他一生征战37年,斩敌百万,创造了长平之战45万赵军全歼的冷兵器时代纪录。若将这位“战神”置于三国群雄逐鹿的舞台,其军事能力将如何与关羽...

2025-07-09

中元节祭祀活动

中元普渡中元节,不少人会在旧历的七月初一到七月卅日之间,择日以酒肉、糖饼、水果等祭品举办祭祀活动,以慰在人世间游玩的众家鬼魂,并祈求自己全年的平安顺利。较为隆重者,甚至请来僧、道诵经作法超度亡魂。也有...

2025-07-09

负荆请罪的主人公:廉颇与蔺相如的将相和传奇

“负荆请罪”是中国历史上极具教育意义的典故,其核心人物为战国时期赵国的两位栋梁之臣——廉颇与蔺相如。这一故事不仅展现了古人以国家利益为重的胸怀,更成为中华文化中“知错能改”“顾全大局”的典范。 典故...

2025-07-09

《水调歌头·游览》译文与赏析

水调歌头·游览宋代:黄庭坚瑶草一何碧,春入武陵溪。溪上桃花无数,枝上有黄鹂。我欲穿花寻路,直入白云深处,浩气展虹霓。只恐花深里,红露湿人衣。坐玉石,倚玉枕,拂金徽。谪仙何处?无人伴我白螺杯。我为灵芝仙...

2025-07-09

赵括的结局:长平悲歌中的血色终章

公元前260年的深秋,山西高平西北的丹河两岸,四十万赵军在断粮四十六日后彻底崩溃。主帅赵括身中数箭,仍率精锐死战突围,最终倒在秦军箭雨之中。这位被后世讥讽为“纸上谈兵”的将领,以生命为代价完成了对“武...

2025-07-09

黄庭坚《清明》翻译与鉴赏

清明宋代:黄庭坚佳节清明桃李笑,野田荒冢只生愁。雷惊天地龙蛇蛰,雨足郊原草木柔。人乞祭余骄妾妇,士甘焚死不公侯。贤愚千载知谁是,满眼蓬蒿共一丘。译文清明时节,桃红李白,含笑盛开。田野上那些长满杂草的坟...

2025-07-09

刘恒代国故地今何在:山西中部的历史密码

公元前196年,年仅八岁的刘恒被汉高祖刘邦封为代王,其封地“代国”成为这位未来汉文帝的龙兴之地。这片土地不仅见证了刘恒从边疆藩王到开明帝王的蜕变,更承载着西汉初期抵御匈奴、休养生息的重要历史记忆。如今...

2025-07-09

寒衣节各地的习俗

寒衣节,是我国祭祀的传统节日。也称为“十月朝”、“祭祖节”、“冥阴节”。寒衣节也意味严冬的到来。下面一起学习了解一下寒衣节的习俗吧。寒衣节农历十月初一,谓之“十月朝”。我国自古以来就有新收时祭奠祖宗的...

2025-07-09