Java中将彩图转换为灰度图的算法
在Android应用开发中有时候可能需要将一张彩色图片变成一张灰度图,除了PS可以达到这种效果以外,我们也可以用代码来实现,以下是Java实现的转换算法:
/**
* 把资源图片转为灰度图
* @param resID 资源ID
* @return
*/
public Bitmap convertGrayImg(int resID) {
Bitmap src=((BitmapDrawable) getResources().getDrawable(resID)).getBitmap();
int w=src.getWidth(),h=src.getHeight();
int[] pix = new int[w * h];
src.getPixels(pix, 0, w, 0, 0, w, h);
int alpha=0xFF<<24;
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
// 获得像素的颜色
int color = pix[w * i + j];
int red = ((color & 0x00FF0000) >> 16);
int green = ((color & 0x0000FF00) >> 8);
int blue = color & 0x000000FF;
color = (red + green + blue)/3;
color = alpha | (color << 16) | (color << 8 ) | color;
pix[w * i + j] = color;
}
}
Bitmap result=Bitmap.createBitmap(w, h, Config.RGB_565);
result.setPixels(pix, 0, w, 0, 0,w, h);
return result;
}
| anyShare分享到: | |
| |
发表在《
发表在《
发表在《
哟西,我也是搞Java开发的。有时间多多交流哈~
[回复]