我一直致力于在java中对图像进行灰度化有一段时间了。我使用的是 colorConvertOp
,但似乎在加载图像完成该过程后,最终 JVM 将在操作中挂起处于锁定状态。
现在我开始使用:
BufferedImage image = new BufferedImage(size, size, BufferedImage.TYPE_BYTE_GRAY);
Graphics g = image.getGraphics();
g.drawImage(img, 0, 0, null);
g.dispose();
但是,我发现 CPU 出现大幅上升,以前低于 20%,现在高达 120%。它似乎还导致我内存泄漏并最终OOM。
是否有一种更简单、更快捷的方法可以在 Java 中进行灰度化,而无需使用尽可能多的 CPU/消除 JVM bug 造成的挂起?
最佳答案
我编写了一个java程序将RGB图像转换为GrayScaleImage。希望这有帮助
public class GrayScale {
BufferedImage image;
int width;
int height;
public GrayScale() {
try {
File input = new File("input path of the image");
image = ImageIO.read(input);
width = image.getWidth();
height = image.getHeight();
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
Color c = new Color(image.getRGB(j, i));
int red = (int) (c.getRed() * 0.299);
int green = (int) (c.getGreen() * 0.587);
int blue = (int) (c.getBlue() * 0.114);
Color newColor = new Color(red + green + blue,
red + green + blue, red + green + blue);
image.setRGB(j, i, newColor.getRGB());
}
}
File ouptut = new File("output path of the image");
ImageIO.write(image, "jpg", ouptut);
} catch (Exception e) {
}
}
static public void main(String args[]) throws Exception {
GrayScale obj = new GrayScale();
}
}
关于Java 灰度图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25855861/