我有一个透明的PNG文件,我用作OpenGL纹理。我使用Bitmap
将其加载到BitmapFactory.decodeResource
,然后将其上传到GPU。
PNG文件相当大,为了减少APK大小,我试图改用两个JPG - 一个是RGB数据,另一个是alpha通道(灰度)。
如何将两个JPG合并在一个Bitmap
对象中并使用Alpha通道?我尝试将Alpha通道加载为Bitmap.Config.ALPHA_8
,然后将它们绘制在彼此之上使用Canvas
但到目前为止没有运气。
答案 0 :(得分:5)
查看Kevin Dion's answer到this related question。他解释了如何组合4个单独的图像(R,G,B和A通道),但您应该能够使其适应两个图像。
答案 1 :(得分:4)
这是一个完整的例子:
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
public class ImageOps {
private static final ColorMatrix sRedToAlphaMatrix = new ColorMatrix(new float[] {
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
1, 0, 0, 0, 0});
private static final ColorMatrixColorFilter sRedToAlphaFilter = new ColorMatrixColorFilter(sRedToAlphaMatrix);
public static Bitmap composeAlpha(Bitmap target, Resources resources, int rgbDrawableId, int alphaDrawableId) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inScaled = false;
// Load RGB data
Bitmap rgb = BitmapFactory.decodeResource(resources, rgbDrawableId, options);
if (target == null) {
// Prepare result Bitmap
target = Bitmap.createBitmap(rgb.getWidth(), rgb.getHeight(), Bitmap.Config.ARGB_8888);
}
Canvas c = new Canvas(target);
c.setDensity(Bitmap.DENSITY_NONE);
// Draw RGB data on our result bitmap
c.drawBitmap(rgb, 0, 0, null);
// At this point, we don't need rgb data any more: discard!
rgb.recycle();
rgb = null;
// Load Alpha data
Bitmap alpha = BitmapFactory.decodeResource(resources, alphaDrawableId, options);
// Draw alpha data on our result bitmap
final Paint grayToAlpha = new Paint();
grayToAlpha.setColorFilter(sRedToAlphaFilter);
grayToAlpha.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
c.drawBitmap(alpha, 0, 0, grayToAlpha);
// Don't need alpha data any more: discard!
alpha.recycle();
alpha = null;
return target;
}
}
答案 2 :(得分:0)
尝试以下操作:迭代两个图像的宽度*高度,并在每个图像上使用Bitmap.getPixel(x,y)。
int alpha = Color.red(grayscaleBitmap.getPixel(x, y)); // grayscale, so any color will do
int red = Color.red(colorBitmap.getPixel(x, y));
int green = Color.green(colorBitmap.getPixel(x, y));
int blue = Color.blue(colorBitmap.getPixel(x, y));
int mergedColor = Color.argb(alpha, red, green, blue);
// save mergedColor in an int[]
然后使用Bitmap.createBitmap(int [] colors,int width,int height,Bitmap.Config config)来创建新的位图。