我正在尝试编写一个方法,它将采用Bitmap
并将其强制为严格的黑白图像(没有灰色阴影)。
我首先将位图传递给使用colormatrix
生成灰度的方法:
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;
}
效果很好而且速度很快..
然后我将它传递给另一种方法来强制灰度图像为2色图像(黑白)这种方法有效,但很明显它会经过每个像素并且需要很长时间:
public Bitmap toStrictBlackWhite(Bitmap bmp){
Bitmap imageOut = bmp;
int tempColorRed;
for(int y=0; y<bmp.getHeight(); y++){
for(int x=0; x<bmp.getWidth(); x++){
tempColorRed = Color.red(imageOut.getPixel(x,y));
Log.v(TAG, "COLOR: "+tempColorRed);
if(imageOut.getPixel(x,y) < 127){
imageOut.setPixel(x, y, 0xffffff);
}
else{
imageOut.setPixel(x, y, 0x000000);
}
}
}
return imageOut;
}
任何人都知道更快更有效的方法吗?
答案 0 :(得分:3)
请勿使用getPixel()
和setPixel()
。
使用getPixels()
将返回所有像素的多维数组。在此阵列上本地执行操作,然后使用setPixels()
设置修改后的阵列。这将明显加快。
答案 1 :(得分:1)
您是否尝试过将其转换为字节数组(请参阅答案here)?
而且,在我调查此问题时,the Android reference for developers about Bitmap processing也可能对您有所帮助。