在Java中设置BufferedImage alpha掩码 [英] Set BufferedImage alpha mask in Java
问题描述
我有两个从pngs加载的BufferedImages。第一个包含一个图像,第二个是图像的alpha蒙版。
我想通过应用alpha蒙版来从这两个图像创建一个组合图像。
我知道如何加载/保存图片,我只需要从两个BufferedImages到一个BufferedImage的位置,右侧是alpha您可以通过一次获取多于一个像素的RGB数据来改进解决方案(请参阅 http://java.sun.com/javase/6/docs /api/java/awt/image/BufferedImage.html ),并且不会在内部循环的每次迭代中创建三个Color对象。
final int width = image.getWidth();
int [] imgData = new int [width];
int [] maskData = new int [width];
for(int y = 0; y< image.getHeight(); y ++){
//从每张图片获取一行数据
image.getRGB(0 ,y,width,1,imgData,0,1);
mask.getRGB(0,y,width,1,maskData,0,1);
//将掩码
用于(int x = 0; x int color = imgData [x]&至0x00FFFFFF; //掩盖任何存在的字母
int maskColor =(maskData [x]& 0x00FF0000)<< 8; //将红色转换为alpha位
color | = maskColor;
imgData [x] = color;
}
//替换数据
image.setRGB(0,y,width,1,imgData,0,1);
}
I have two BufferedImages I loaded in from pngs. The first contains an image, the second an alpha mask for the image.
I want to create a combined image from the two, by applying the alpha mask. My google-fu fails me.
I know how to load/save the images, I just need the bit where I go from two BufferedImages to one BufferedImage with the right alpha channel.
Your solution could be improved by fetching the RGB data more than one pixel at a time(see http://java.sun.com/javase/6/docs/api/java/awt/image/BufferedImage.html), and by not creating three Color objects on every iteration of the inner loop.
final int width = image.getWidth();
int[] imgData = new int[width];
int[] maskData = new int[width];
for (int y = 0; y < image.getHeight(); y++) {
// fetch a line of data from each image
image.getRGB(0, y, width, 1, imgData, 0, 1);
mask.getRGB(0, y, width, 1, maskData, 0, 1);
// apply the mask
for (int x = 0; x < width; x++) {
int color = imgData[x] & 0x00FFFFFF; // mask away any alpha present
int maskColor = (maskData[x] & 0x00FF0000) << 8; // shift red into alpha bits
color |= maskColor;
imgData[x] = color;
}
// replace the data
image.setRGB(0, y, width, 1, imgData, 0, 1);
}
这篇关于在Java中设置BufferedImage alpha掩码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!