这适用于较低的 Api,试试吧
public Bitmap toGrayscale(Bitmap bmpOriginal)
{
int width, height;
height = bmpOriginal.getHeight();
width = bmpOriginal.getWidth();
Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Canvas c = new Canvas(bmpGrayscale);
Paint paint = new Paint();
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
paint.setColorFilter(f);
c.drawBitmap(bmpOriginal, 0, 0, paint);
return bmpGrayscale;
}
如果您想使用画布或画家使用此代码,则无法为您的代码获取灰度图像,因为您使用了不可变的可绘制对象
Bitmap immutableBitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.my_drawable);
Bitmap mutableBitmap = immutableBitmap.copy(Bitmap.Config.ARGB_8888, true);
//you have two bitmaps in memory, so clean up the mess a bit
immutableBitmap.recycle(); immutableBitmap=null;
Drawable d = new BitmapDrawable(mutableBitmap);
//mutate it
d.setColorFilter(new LightingColorFilter(color, lightenColor));
imageView.setImageDrawable(d);