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 << 16 | rgb << 8 | 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 < pixels.length; i++) {
int pixel = pixels[i];
int row = i / w;
int col = i % w;
if (color != null) {
if (pixel != 0) {
pixel = filter(pixel, color);
}
}
bi.setRGB(col, row, pixel);
}
return bi;
} else {
return null;
}
}
}
}
如何才能看懂别人写的位运算代码?
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
4条回答 默认 最新
- danielinbiti 2015-03-04 13:56关注
你要理解RGB的2进制格式,R,G,B的取值范围是0-255,如果是ARGB,前面还有一个透明度0-255。255在2进制中占8位,也就是
ARGB像素格式(左边最高位,右边最低位):00000000RRRRRRRRGGGGGGGGBBBBBBBB。
到这个格式你那位移就清楚了,取A得值,只要后面24位都置成0,前8位为1,做与就行了。当然你要>>24&0xff也可以,只是没必要。>>24后,再最后处理完灰度后还得<<24回来。
取R,G,B都一样原理。本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
- ¥30 截图中的mathematics程序转换成matlab
- ¥15 动力学代码报错,维度不匹配
- ¥15 Power query添加列问题
- ¥50 Kubernetes&Fission&Eleasticsearch
- ¥15 報錯:Person is not mapped,如何解決?
- ¥15 c++头文件不能识别CDialog
- ¥15 Excel发现不可读取的内容
- ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
- ¥20 yolov5自定义Prune报错,如何解决?