我的要求是,我需要将彩色图像转换为灰度图像并将灰度图像的像素值获取到数组并对该数组执行一些加密算法并再次使用这个更改后的像素数组,我需要转换返回/创建灰度图像并显示它。 这是我的疑惑。
使用彩色图像,我获得了三个不同数组中的 RGB 像素值。据我所知,可以通过
red+green+blue/3=gray
获得灰度像素。这里的红、蓝、绿、灰是二维数组。这种获取灰度像素值的方式是否正确?gray[x][y] = (r[x][y]+g[x][y]+b[x][y])/3;
如果这是正确的,那么我可以轻松地对该数组执行算法。真正的问题出现在这里。如何使用该像素阵列转换回/创建灰度图像。展示如何使用像素值创建灰度图像的示例将非常有帮助。谢谢。
for(int x = 0;x<=height;x++) { for(int y = 0;y<=width;y++) { gray[x][y] = (r[x][y]+g[x][y]+b[x][y])/3; System.out.print(gray[x][y]+"\t"); } System.out.println(" "); }
最佳答案
我建议创建一个新的 TYPE_BYTE_GRAY 的 BufferedImage,而不是通过自己操作像素将图像转换为灰度。然后就可以直接操作像素了。
public static BufferedImage convertToGray(BufferedImage biColor)
{
BufferedImage biGray = new BufferedImage(biColor.getWidth(), biColor.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
biGray.getGraphics().drawImage(biColor, 0, 0, null);
return biGray;
}
public static void manipulatePixels(BufferedImage biGray)
{
byte [] imageData = ((DataBufferByte)biGray.getRaster().getDataBuffer()).getData();
for (int i = 0; i < imageData.length; i++)
{
// do manipulation/encryption here - or on the entire array at once
}
}
如果出于某种原因你想从字节数组创建一个全新的图像,只需创建一个新图像并将像素复制到它的字节数组中。
public static BufferedImage createImageFromArray(byte[] imageData, int width, int height)
{
BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
byte [] newData = ((DataBufferByte) newImage.getRaster().getDataBuffer()).getData();
for (int i = 0; i < imageData.length; i++)
{
newData[i] = imageData[i];
}
return newImage;
}
关于java - 如何使用java从像素值创建灰度图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29281358/