我正在尝试解决图像被读取的问题。我需要排除像素中的蓝色通道,这样就会产生RG图像。
这是我到目前为止所做的并且没有工作D;
我是否需要创建一个新的BufferedImage并将每个平均像素(没有蓝色通道)应用于它?我不知道怎么做。
答案 0 :(得分:2)
首先,将您的倒数第二行代码更改为此,看看是否有帮助:
image.setRGB(i, j, (redData[i][j] << 16) | (greenData[i][j] << 8));
但是有了这个,你最终会得到一张与原版相同尺寸的图像,除了你放弃蓝色通道而你平均超过其他通道(类似于模糊),但仅限于每个2x2块的左上角。
如果您想要实际创建四分之一大小的图像,确实需要创建一个宽度和高度减半的新BufferedImage
,然后将上面提到的行更改为:
newImage.setRGB(i/2, j/2, (redData[i][j] << 16) | (greenData[i][j] << 8));
以下是应该执行此操作的代码的更新版本(未经测试):
public static BufferedImage isolateBlueChannelAndResize(BufferedImage image) {
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();
// Round down for odd-sized images to prevent indexing outside image
if ((imageWidth & 1) > 0) imageWidth --;
if ((imageHeight & 1) > 0) imageHeight--;
BufferedImage newImage = new BufferedImage(imageWidth/2, imageHeight/2, image.getType());
for (int i = 0; i < imageWidth; i += 2) {
for (int j = 0; j < imageHeight; j += 2) {
int r1 = (image.getRGB(i , j ) >> 16) & 0xff;
int r2 = (image.getRGB(i+1, j ) >> 16) & 0xff;
int r3 = (image.getRGB(i , j+1) >> 16) & 0xff;
int r4 = (image.getRGB(i+1, j+1) >> 16) & 0xff;
int red = (r1 + r2 + r3 + r4 + 3) / 4; // +3 rounds up (equivalent to ceil())
int g1 = (image.getRGB(i , j ) >> 8) & 0xff;
int g2 = (image.getRGB(i+1, j ) >> 8) & 0xff;
int g3 = (image.getRGB(i , j+1) >> 8) & 0xff;
int g4 = (image.getRGB(i+1, j+1) >> 8) & 0xff;
int green = (g1 + g2 + g3 + g4 + 3) / 4; // +3 rounds up (equivalent to ceil())
newImage.setRGB(i/2, j/2, (red << 16) | (green << 8));
}
}
return newImage;
}
答案 1 :(得分:0)
我真的认为更简单的方法是使用Color
类:
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class AverageOutBlue {
public static final float AVG_FACTOR = 1f / (4f * 255f);
public static BufferedImage processImage(final BufferedImage src) {
final int w = src.getWidth();
final int h = src.getHeight();
final BufferedImage out = new BufferedImage(w / 2, h / 2, src.getType());
for (int i = 0; i < w; i += 2)
for (int j = 0; j < h; j += 2) {
final Color color = avgColor(src, i, j);
out.setRGB(i / 2, j / 2, color.getRGB());
}
return out;
}
private static Color avgColor(final BufferedImage src, final int i,
final int j) {
final Color c1 = new Color(src.getRGB(i, j));
final Color c2 = new Color(src.getRGB(i + 1, j));
final Color c3 = new Color(src.getRGB(i + 1, j));
final Color c4 = new Color(src.getRGB(i + 1, j + 1));
final float r = (c1.getRed() + c2.getRed() + c3.getRed() + c4.getRed())
* AVG_FACTOR;
final float g = (c1.getGreen() + c2.getGreen() + c3.getGreen() +
c4.getGreen()) * AVG_FACTOR;
return new Color(r, g, 0f);
}
}