鴻蒙HarmonyOS三方件開(kāi)發(fā)指南(7)-compress組件
想了解更多內(nèi)容,請(qǐng)?jiān)L問(wèn):
51CTO和華為官方合作共建的鴻蒙技術(shù)社區(qū)
https://harmonyos.51cto.com/#zz
1. 組件compress功能介紹
1.1. 組件介紹:
compress是一個(gè)輕量級(jí)圖像壓縮庫(kù)。compress允許將大照片壓縮成小尺寸的照片,圖像質(zhì)量損失非常小或可以忽略不計(jì)。
1.2. 手機(jī)模擬器上運(yùn)行效果:

2. 組件compress使用方法
2.1. 添加依賴
將compress-debug.har復(fù)制到應(yīng)用的entry\libs目錄下即可(由于build.gradle中已經(jīng)依賴的libs目錄下的*.har,因此不需要再做修改)。
2.2. 設(shè)置布局
- <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
參數(shù):
context - 應(yīng)用程序上下文
file - 待壓縮圖片抽象路徑名
width - 壓縮后寬度
height - 壓縮后高度
quality - 圖片壓縮質(zhì)量,范圍0~100
結(jié)果:
返回壓縮后圖片抽象路徑名。
異常:
發(fā)生I/O異常
(2)默認(rèn)壓縮:
- public static File defaultCompress(Context context, File file) throws IOException
參數(shù):
context - 應(yīng)用程序上下文
file - 待壓縮圖片抽象路徑名
結(jié)果:
返回壓縮后圖片抽象路徑名。
異常:
發(fā)生I/O異常
簡(jiǎn)單示例:
運(yùn)行示例前需要在模擬器保存一張截圖或使用相機(jī)功能照一張照片
- public void onStart(Intent intent) {
- super.onStart(intent);
- super.setUIContent(ResourceTable.Layout_ability_main);
- // 請(qǐng)求文件的讀取權(quán)限
- String[] permissions = {"ohos.permission.READ_USER_STORAGE"};
- requestPermissionsFromUser(permissions, 0);
- // 獲取壓縮按鈕并綁定事件
- Button button = (Button) findComponentById(ResourceTable.Id_button);
- if (button != null) {
- // 為按鈕設(shè)置點(diǎn)擊回調(diào)
- 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");
- // 默認(rèn)壓縮
- // 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) {
- // 為按鈕設(shè)置點(diǎn)擊回調(diào)
- 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()) {
- // 互毆媒體庫(kù)的圖片
- 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);
- // 根據(jù)圖片的uri打開(kāi)文件并保存到臨時(shí)目錄中
- 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開(kāi)發(fā)實(shí)現(xiàn)
3.1. 拷貝圖片制臨時(shí)目錄
傳入的圖片路徑拷貝臨時(shí)文件到應(yīng)用的臨時(shí)目錄。
- 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; // 壓縮質(zhì)量
- refreshTmpFile(pixelMap, cacheFile, quality);
- return cacheFile;
- }
3.2. 圖片解碼
對(duì)臨時(shí)目錄里的圖片進(jìn)行解碼
- 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. 圖片編碼
按照開(kāi)發(fā)人員設(shè)定的規(guī)則進(jìn)行編碼,生成新圖片
- 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();
- }
項(xiàng)目源代碼地址:https://github.com/isoftstone-dev/Compressor_Harmony
歡迎交流:HOS@isoftstone.com
©著作權(quán)歸作者和HarmonyOS技術(shù)社區(qū)共同所有,如需轉(zhuǎn)載,請(qǐng)注明出處,否則將追究法律責(zé)任。
想了解更多內(nèi)容,請(qǐng)?jiān)L問(wèn):
51CTO和華為官方合作共建的鴻蒙技術(shù)社區(qū)
https://harmonyos.51cto.com/#zz