我仍然无法使用 Java 保存灰度图像。我怎么能这样做? 格式不是很重要,但不应该有图像压缩。
有人知道吗?
最佳答案
这可能不是最优雅的方法,但它会起作用:
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageTest {
public static void main(String[] args) throws IOException {
int width = 10 // width of your image
int height = 10 // height of your image
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; ++x)
{
for (int y = 0; y < height; ++y)
{
int grayscale = ... // get your greyscale value 0..255 from your array here.
int colorValue = grayscale | grayscale << 8 | grayscale << 16;
img.setRGB(x, y, colorValue);
}
}
ImageIO.write(img, "png", new File("output.png"));
}
}
colorValue 由 r、g 和 b 组成(b 在最低字节上,g 前一位,r 前一位)。由于您的图像是灰度的,您可以简单地为图像使用相同的 r、g 和 b 值,因此您可以简单地执行以下操作:
int colorValue = grayscale | grayscale << 8 | grayscale << 16;
关于java - 灰度图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2216637/