Android縮放drawable 壓縮圖片 matrix
Q:加載時圖片時有一些圖片太大,導致內存溢出,想把這些圖片壓縮成一個縮略圖,該怎麼做?不能隻是縮小圖片大小,而是要把體積降下來,幾百K的圖片壓縮成幾K或幾百B.
A1:
壓縮圖片質量:
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, fos);
其中的quality為0~100, 可以壓縮圖片質量, 不過對於大圖必須對圖片resize
這個是等比例縮放:
bitmap = Bitmap.createScaledBitmap(bitmap, width, height, false);
newBitmap = Bitmap.createBitmap(oldBitmap, 0, 0, width, height, matrix, true);//用距陣的方式縮放
這個是截取圖片某部分:
bitmap = Bitmap.createBitmap(bitmap, x, y, width, height);
這幾個方法都是針對Bitmap的, 不過鑒於Bitmap可以從file中讀取, 也可以寫入file.
這是我知道Android自帶庫裏中唯一可以縮放和壓縮的圖片方法.
--------------------------------------------------------------------------------------------------------------------------------------------------
A2:
內存溢出,你這麼處理就可以。用完及時回收
BitmapFactory.Options options = new BitmapFactory.Options();
options.inTempStorage = new byte[16*1024];
Bitmap bitmapImage = BitmapFactory.decodeFile(path,opt);
A:很多網友可能發現了Android的Bitmap對象無法保存成為一個bmp文件,即提供的方法隻有compress(Bitmap.CompressFormat format, int quality, OutputStream stream) ,可以存為png和jpg,png可能還好說,但是jpg是有損壓縮會降低圖片的質量,其實Google還提供了一個API在Bitmap類,通過copyPixelsToBuffer(Buffer dst) 這個方法來解決,Buffer類型,和前幾天我們說到的NIO中的ByteBuffer處理方式一樣,需要說明的是java中的Buffer在內存中是連續成塊的,同時底層有C++支持效率還是很高的。
通過copyPixelsToBuffer(Buffer dst) 方法將會返回一個RGB8888格式的DIB文件,DIB位圖和設備無關,這裏Android123提醒大家,如果想顯示出位圖,還需要將其加上位圖的文件頭才行。
Q:Android縮放drawable Matrix
一、 相關概念
1. Drawable 就是一個可畫的 對象,其可能是一張位圖( BitmapDrawable ),也可能是一個 圖形(ShapeDrawable ),還有可能是一 個圖層( LayerDrawable ),我們根據畫圖的需求,創建相應的可畫對象
2. Canvas 畫布,繪製的目 的區域,用於繪圖
3. Bitmap 位圖,用於圖的 處理
4. Matrix 矩陣,此例中用 於操作圖片
二、 步驟
1. 把 drawable 畫到位圖對象上
2. 對位圖對象做縮放(或旋轉等)操作
3. 把位圖再轉換成 drawable
三、 示例
static Bitmap drawableToBitmap(Drawable drawable) // drawable 轉換成 bitmap { int width = drawable.getIntrinsicWidth(); // 取 drawable 的長寬 int height = drawable.getIntrinsicHeight(); Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888:Bitmap.Config.RGB_565; // 取 drawable 的顏色格式 Bitmap bitmap = Bitmap.createBitmap(width, height, config); // 建立對應 bitmap Canvas canvas = new Canvas(bitmap); // 建立對應 bitmap 的畫布 drawable.setBounds(0, 0, width, height); drawable.draw(canvas); // 把 drawable 內容畫到畫布中 return bitmap; } static Drawable zoomDrawable(Drawable drawable, int w, int h) { int width = drawable.getIntrinsicWidth(); int height= drawable.getIntrinsicHeight(); Bitmap oldbmp = drawableToBitmap(drawable); // drawable 轉換成 bitmap Matrix matrix = new Matrix(); // 創建操作圖片用的 Matrix 對象 float scaleWidth = ((float)w / width); // 計算縮放比例 float scaleHeight = ((float)h / height); matrix.postScale(scaleWidth, scaleHeight); // 設置縮放比例 Bitmap newbmp = Bitmap.createBitmap(oldbmp, 0, 0, width, height, matrix, true); // 建立新的 bitmap ,其內容是對原 bitmap 的縮放後的圖 return new BitmapDrawable(newbmp); // 把 bitmap 轉換成 drawable 並返回 } }
最後更新:2017-04-02 16:47:34