[英]How do I save a BufferedImage to a pgm file?
I looked through the internet but I could not find an answer.我浏览了互联网,但找不到答案。 I have a pgm file which I use as a BufferedImage to do a convolution (I use JAI for that) but I am having trouble in saving it back to a pgm file.
我有一个 pgm 文件,我将其用作 BufferedImage 来进行卷积(为此我使用了 JAI),但是我无法将其保存回 pgm 文件。 So far I used following code to save:
到目前为止,我使用以下代码来保存:
JAI.create("filestore", newImage, outputFileName);
With that I get a pgm file but when I open the image IfranView tells me that it is a TIF file with incorrect extension.有了它,我得到了一个 pgm 文件,但是当我打开图像时 IfranView 告诉我它是一个扩展名不正确的 TIF 文件。 What do I need to change?
我需要改变什么?
I appreciate any help!我感谢任何帮助! Please provide code examples if possible.
如果可能,请提供代码示例。 Thanks everyone.
谢谢大家。
Kind regards, Staniel亲切的问候,斯坦尼尔
BufferedImage bufferedImage = ImageIO.read(new File("input file directory...image.png"));
ImageIO.write(bufferedImage, "pgm", new File("output file directory.....image.pgm"));
This should take a buffered image (jpeg, png...etc) and convert it properly to a pgm.这应该采用缓冲图像(jpeg、png...等)并将其正确转换为 pgm。
EDIT: The JAI Plugin which allows for .pgm files to be used with ImageIO can be found at http://www.oracle.com/technetwork/java/index.html编辑:允许 .pgm 文件与 ImageIO 一起使用的 JAI 插件可以在http://www.oracle.com/technetwork/java/index.html找到
Here's an example I found.这是我找到的一个例子。 Not tested.
未测试。
// Create the OutputStream.
OutputStream out = new FileOutputStream(fileToWriteTo);
// Create the ParameterBlock.
PNMEncodeParam param = new PNMEncodeParam();
param.setRaw(true.equals("raw"));
//Create the PNM image encoder.
ImageEncoder encoder = ImageCodec.createImageEncoder("PNM", out, param);
See Writing PNM Files .请参阅编写 PNM 文件。
I found the answer.我找到了答案。 I already added the external JAI imageio to my library.
我已经将外部 JAI imageio 添加到我的库中。
ImageIO.write(bufferedImage, "pnm", new File("output file directory.....image.pgm"));
Instead of "pgm" it should say "pnm".应该说“pnm”而不是“pgm”。 The new file will automatically have the pgm extension.
新文件将自动具有 pgm 扩展名。
Maybe late, but I just wrote one.也许晚了,但我刚写了一篇。 A simple PGM writer taking a 2d-double array with values in range [0.0,1.0].
一个简单的 PGM 编写器,采用值在 [0.0,1.0] 范围内的 2d-double 数组。
public static void WritePGM(string fileName, double[,] bitmap)
{
var width = bitmap.GetLength(0);
var height = bitmap.GetLength(1);
var header = "P5\n" + width + " " + height + "\n255\n";
var writer = new BinaryWriter(new FileStream(fileName, FileMode.Create));
writer.Write(System.Text.Encoding.ASCII.GetBytes(header));
for (var j = 0; j < height; j++)
{
for (var i = width-1; i >= 0; i--)
{
var c = (byte)(System.Math.Max(System.Math.Min(1.0, bitmap[i, j]), 0.0) * 255.0);
writer.Write(c);
}
}
writer.Close();
}
您可以在这里找到外部JAI ImageIO库: https : //bintray.com/jai-imageio/maven/jai-imageio-core-standalone/view
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.