java - 如何将基于浮点的图像写入文件?

标签 java image javax.imageio

使用找到的代码here ,我编写了存储图像数据的代码,其中每个颜色分量都是浮点值。

// Create a TYPE_FLOAT sample model (specifying how the pixels are stored)
SampleModel sampleModel = new PixelInterleavedSampleModel(DataBuffer.TYPE_FLOAT, options.width, options.height, 4, options.width * 4, new int[]{0,1,2,3});
// ...and data buffer (where the pixels are stored)
DataBufferFloat buffer = new DataBufferFloat(options.width * options.height * 4);

// Wrap it in a writable raster
WritableRaster raster = Raster.createWritableRaster(sampleModel, buffer, null);

// Create a color model compatible with this sample model/raster (TYPE_FLOAT)
// Note that the number of bands must equal the number of color components in the 
// color space (3 for RGB) + 1 extra band if the color model contains alpha 
ColorSpace colorSpace = ColorSpace.getInstance(ColorSpace.CS_sRGB);
ColorModel colorModel = new ComponentColorModel(colorSpace, true, false, Transparency.TRANSLUCENT, DataBuffer.TYPE_FLOAT);

// And finally create an image with this raster
BufferedImage out = new BufferedImage(colorModel, raster, colorModel.isAlphaPremultiplied(), null);
float[] backingImageData = buffer.getData();

FloatBuffer data = /*External Image Data Source...*/;
data.get(backingImageData); //Place data in image

boolean writerFound = ImageIO.write(out, "png", new File("C:\\out.png"));

但是,此代码失败,因为 ImageIO 无法为此自定义图像配置找到合适的编写器(如调试时所示,其中 writerFoundfalse )。如何让 ImageIO 成功地用该图像写入数据?

最佳答案

要将包含浮点值的图像写入文件,您需要:

a) 允许存储浮点值的格式。大多数图像格式(包括 JPEG、PNG 或 GIF)当然不支持。据我所知,最常用的文件格式是 TIFF。不过,值得注意的是,浮点 TIFF 不是“基线”TIFF,因此并非所有 TIFF 软件都支持此类文件。

b) 一个ImageIO插件,支持以浮点形式写入TIFF。我认为 JAI 可能会起作用,并且非常肯定 GeoTools 也能起作用。我自己的插件目前支持读取,但不支持写入浮点(但如果您喜欢冒险,为此创建更改集应该相当容易)。

排序后,以下内容应该可以工作(假设 out 与代码中的浮点图像相同):

ImageIO.write(out, "TIFF", new File("C:\\out.tif"));

关于java - 如何将基于浮点的图像写入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60460417/

相关文章:

java - 应用引擎java : debugging servlet

java - 图像读取大小异常 : I/O error reading PNG header!

java - 如何更改从文件加载的 BufferedImage 的图像类型?

java - ImageIO 在最大速度下比 GZIPStream 更快

java - 使用 ImageIO.read() 时更改颜色

java.net.SocketTimeoutException : failed to connect

Java套接字编程: Send Object as CSV or Serialized Object?

java - 在 Flyway Java API 中使用 SQL 迁移文件

Silverlight:动画和/或平移图像

c++ - 用 QGraphicsScene 和 QGraphicsView 平铺