我正在尝试解决读取图像的问题。我需要排除像素中的蓝色通道,以免产生RG图像。

这是我到目前为止没有用的D;

我是否需要创建一个新的BufferedImage并将每个平均像素(没有蓝色通道)应用到它?我不确定该怎么做。

最佳答案

首先,将倒数第二行的代码更改为此,然后查看是否有帮助:

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;
}

关于java - 平均数组中的像素数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23039115/

10-10 17:59
查看更多