我有一張灰度JPG圖片,我想將其加載到格式爲Bitmap.Config.ALPHA_8
的位圖中。這是可能的,我該怎麼做?如何將灰度位圖轉換爲alpha蒙版?
從PNG(可以有空的R,G,B通道)加載alpha通道很簡單,但我想用JPG進行壓縮。
這是一個後續問題How to combine two opaque bitmaps into one with alpha channel?
我有一張灰度JPG圖片,我想將其加載到格式爲Bitmap.Config.ALPHA_8
的位圖中。這是可能的,我該怎麼做?如何將灰度位圖轉換爲alpha蒙版?
從PNG(可以有空的R,G,B通道)加載alpha通道很簡單,但我想用JPG進行壓縮。
這是一個後續問題How to combine two opaque bitmaps into one with alpha channel?
ColorMatrix營救!
引述的Android文檔,嘉洛斯:
用於轉化的位圖的 顏色+ alpha分量5x4的矩陣。矩陣被存儲在單個陣列中,並且其處理如下:[ a,b,c,d,e,f,g,h,i,j,k,l,m, n,o,當應用於 顏色[r,g,b,a]時,得到的顏色被計算爲(在鉗位後) R'= a R + b G + c B + d A + e; G'= f R + g G + h B + i A + j; B'= k R + l G + m B + n A + o; A'= p R + q G + r B + s A + t;
設置從紅色通道(或綠色,或藍色,對灰度無關緊要)採用alpha值的顏色矩陣,然後在Paint.setColorFilter()
中使用它。下面是一個或多或少的完整示例:
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inScaled = false;
// Load source grayscale bitmap
Bitmap grayscale = BitmapFactory.decodeResource(getResources(), R.drawable.my_grayscale_mask, options);
// Place for alpha mask. It's specifically ARGB_8888 not ALPHA_8,
// ALPHA_8 for some reason didn't work out for me.
Bitmap alpha = Bitmap.createBitmap(grayscale.getWidth(), grayscale.getHeight(),
Bitmap.Config.ARGB_8888);
float[] matrix = new float[] {
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
1, 0, 0, 0, 0};
Paint grayToAlpha = new Paint();
grayToAlpha.setColorFilter(new ColorMatrixColorFilter(new ColorMatrix(matrix)));
Canvas alphaCanvas = new Canvas(alpha);
// Make sure nothing gets scaled during drawing
alphaCanvas.setDensity(Bitmap.DENSITY_NONE);
// Draw grayscale bitmap on to alpha canvas, using color filter that
// takes alpha from red channel
alphaCanvas.drawBitmap(grayscale, 0, 0, grayToAlpha);
// Bitmap alpha now has usable alpha channel!
無論這個矩陣是否只將紅色通道從掩碼中取出?當然,如果源代碼真的是灰色的,這應該起作用。 mactix對於普通的RGB看起來如何?在我的底線「0.333,0.333,0.334,0,0」中,我想。是對的嗎? – 2015-02-23 08:12:06