使用 BufferedImage 时灰度图像变为单色
Grayscale image becomes monochrome when using BufferedImage
我需要编写一个程序来拍摄图像,调整大小并旋转它,然后将其保存出来。前两点已经完成,但现在我遇到了问题。每次我转换灰度图像时,它都会变成单色图像。
我使用以下命令加载目标图像:
BufferedImage sourceimg = ImageIO.read(input);
在缩放和旋转它之后,我使用以下命令将其保存:
BufferedImage newimg = new BufferedImage(sourceimg.getHeight(), sourceimg.getWidth(), sourceimg.getType());
op.filter(sourceimg, newimg);
sourceimg = newimg;
ImageIO.write(sourceimg, "png", outputFile);
这适用于除灰度图像之外的所有图像。我已经通过将每个图像的类型设置为 ARGB 来尝试解决方法,但必须有另一种方法。有没有办法获取给定图像的 IndexColorModel?
问题已经解决,我只需要更改:
BufferedImage newimg = new BufferedImage(sourceimg.getHeight(), sourceimg.getWidth(), sourceimg.getType());
至:
BufferedImage newimg = new BufferedImage(sourceimg.getWidth(), sourceimg.getHeight(), BufferedImage.TYPE_INT_ARGB);
还有其他解决方案,特别是如果您想保留原始图像类型(即保留 IndexColorModel
图像的调色板等)。
其实最简单的就是直接做(假设op
是标准的BufferedImageOp
):
BufferedImage newimg = op.filter(sourceimg, null);
此处将为您创建一个新的兼容图像,其大小正确以保留操作结果。
另一个选项,将保留图像类型和颜色模型,稍微更冗长:
ColorModel sourceCM = sourceimg.getColorModel(); // Will be the IndexColorModel in your case
// I'm assuming you are deliberately switching width/height to rotate 90 deg
WritableRaster raster = sourceCM.createCompatibleWritableRaster(sourceimg.getHeight(), sourceimg.getWidth());
BufferedImage newimg = new BufferedImage(sourceCM, raster, sourceCM.isAlphaPremultiplied(), null);
op.filter(sourceimg, newimg);
我需要编写一个程序来拍摄图像,调整大小并旋转它,然后将其保存出来。前两点已经完成,但现在我遇到了问题。每次我转换灰度图像时,它都会变成单色图像。 我使用以下命令加载目标图像:
BufferedImage sourceimg = ImageIO.read(input);
在缩放和旋转它之后,我使用以下命令将其保存:
BufferedImage newimg = new BufferedImage(sourceimg.getHeight(), sourceimg.getWidth(), sourceimg.getType());
op.filter(sourceimg, newimg);
sourceimg = newimg;
ImageIO.write(sourceimg, "png", outputFile);
这适用于除灰度图像之外的所有图像。我已经通过将每个图像的类型设置为 ARGB 来尝试解决方法,但必须有另一种方法。有没有办法获取给定图像的 IndexColorModel?
问题已经解决,我只需要更改:
BufferedImage newimg = new BufferedImage(sourceimg.getHeight(), sourceimg.getWidth(), sourceimg.getType());
至:
BufferedImage newimg = new BufferedImage(sourceimg.getWidth(), sourceimg.getHeight(), BufferedImage.TYPE_INT_ARGB);
还有其他解决方案,特别是如果您想保留原始图像类型(即保留 IndexColorModel
图像的调色板等)。
其实最简单的就是直接做(假设op
是标准的BufferedImageOp
):
BufferedImage newimg = op.filter(sourceimg, null);
此处将为您创建一个新的兼容图像,其大小正确以保留操作结果。
另一个选项,将保留图像类型和颜色模型,稍微更冗长:
ColorModel sourceCM = sourceimg.getColorModel(); // Will be the IndexColorModel in your case
// I'm assuming you are deliberately switching width/height to rotate 90 deg
WritableRaster raster = sourceCM.createCompatibleWritableRaster(sourceimg.getHeight(), sourceimg.getWidth());
BufferedImage newimg = new BufferedImage(sourceCM, raster, sourceCM.isAlphaPremultiplied(), null);
op.filter(sourceimg, newimg);