目錄:java
2. 組件compress使用方法github
1. 組件compress功能介紹
1.1. 組件介紹:
compress是一個輕量級圖像壓縮庫。compress容許將大照片壓縮成小尺寸的照片,圖像質量損失很是小或能夠忽略不計。dom
1.2. 手機模擬器上運行效果:
ide
2. 組件compress使用方法
2.1. 添加依賴
將compress-debug.har複製到應用的entry\libs目錄下便可(因爲build.gradle中已經依賴的libs目錄下的*.har,所以不須要再作修改)。佈局
2.2. 設置佈局post
<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. 圖像壓縮
核心類:Compressorgradle
核心方法:ui
(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