我有一张灰度JPG图片,我想将其加载到格式Bitmap.Config.ALPHA_8
的位图中。这可能吗,我怎么能这样做?
从PNG(可以有空R,G,B通道)加载alpha通道很简单,但我想用JPG进行压缩。
这是How to combine two opaque bitmaps into one with alpha channel?
的后续问题答案 0 :(得分:10)
ColorMatrix来救援!
引用Android文档,ColorMatrix:
5x4矩阵用于转换 颜色+位图的alpha分量。 矩阵存储在单个中 数组,其处理如下:[ a,b,c,d,e,f,g,h,i,j,k,l,m, n,o,p,q,r,s,t]当应用于 颜色[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!