当前位置 博文首页 > 如何才能看懂别人写的位运算代码?_weixin_39809168的博客:java
import?java.awt.Color;
import?java.awt.Image;
import?java.awt.image.BufferedImage;
import?java.awt.image.PixelGrabber;
/**
*?我知道位运算是什么,怎么运算的,但我实在看不懂别人写的位运算代码,求高人指点我如何才能看懂别人写的位运算代码?
*
*?希望能得到详细的回答,除了将这个类的所有位运算都解释一遍,还请将位运算在java图像处理中有哪些应用告诉我,谢谢!
*/
public?class?DyedImageUtils?{
/**
*?根据指定颜色过滤像素
*
*?@param?pixel
*?@param?filterColor
*?@return
*/
private?static?int?filter(int?pixel,?Color?filterColor)?{
int?alpha?=?pixel?>>?24?&?0xff;//?为什么要将pixel进行">>?24"呢,又为什么要"&?0xff"呢,能解释解释这句代码的意义吗?
if?(alpha?>?0)?{
pixel?=?gray(pixel);
return?pixel?&?filterColor.getRGB();//?同上,这句"按位与"的代码我也不明白为什么要这么做
}?else?{
return?0;
}
}
/**
*?处理颜色灰度
*
*?@param?rgb
*?@return
*/
private?static?int?gray(int?rgb)?{
int?a?=?rgb?&?0xff000000;//?同上,这句"按位与"的代码我也不明白为什么要这么做
int?r?=?rgb?>>?16?&?0xff;//?同上,不明白为什么要这么做
int?g?=?rgb?>>?8?&?0xff;//?同上
int?b?=?rgb?&?0xff;//?同上
rgb?=?r?*?77?+?g?*?151?+?b?*?28?>>?8;//?同上
return?a?|?rgb?<
}
/**
*?对图片进行着色
*
*?@param?image
*?@param?color
*?@return
*/
public?static?Image?createDyedImage(Image?image,?Color?color)?{
if?(color?==?null)?{
return?image;
}?else?{
if?(image?!=?null)?{
int?w?=?image.getWidth(null);
int?h?=?image.getHeight(null);
int[]?pixels?=?new?int[w?*?h];
PixelGrabber?pg?=?new?PixelGrabber(image,?0,?0,?w,?h,?pixels,?0,?w);
try?{
pg.grabPixels();
}?catch?(InterruptedException?ex)?{
ex.printStackTrace();
return?null;
}
BufferedImage?bi?=?new?BufferedImage(w?>?1???w?:?1,?h?>?1???h?:?1,?BufferedImage.TYPE_INT_ARGB);
for?(int?i?=?0;?i?
int?pixel?=?pixels[i];
cs