我一直在尝试使用 javax.imageio 以编程方式从 Java 中的许多其他 png 文件创建一个 png 文件。
特别是我一直在尝试使用如何将多个 png 图像转换为单个 tiff 文件中概述的答案
但是,当我调用该writeInsert(..)
方法时,我不断收到以下异常。
java.lang.UnsupportedOperationException: Unsupported write variant!
at javax.imageio.ImageWriter.unsupported(Unknown Source)
at javax.imageio.ImageWriter.writeInsert(Unknown Source)
我知道canInsertImage
返回是否可以插入(我可以看到此方法返回 false)但是我不知道如何更改它。
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
public class ImageTest
{
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException
{
ImageOutputStream ios = null;
ImageWriter writer = null;
try
{
String dirName = "C:/png/test";
File dir = new File(dirName);
if (dir.exists() && dir.isDirectory())
{
File[] files = dir.listFiles();
if (null != files && files.length > 0)
{
File outFile = new File("C:/png", "output.png");
ios = ImageIO.createImageOutputStream(outFile);
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("png");
if (null != writers && writers.hasNext())
{
writer = writers.next();
writer.setOutput(ios);
ImageWriteParam param = writer.getDefaultWriteParam();
for (int i = 0; i < files.length; i++)
{
InputStream fis = null;
try
{
fis = new BufferedInputStream(new FileInputStream(files[i]));
BufferedImage image = ImageIO.read(fis);
IIOImage img = new IIOImage(image, null, null);
if (i == 0)
{
writer.write(null, img, param);
}
else
{
writer.writeInsert(-1, img, param);
}
image.flush();
} finally
{
if (null != fis)
{
fis.close();
}
}
}
}
}
}
} catch (Exception e)
{
System.err.println("OOOps: " + e.getMessage() + "\n");
e.printStackTrace();
} finally
{
if (null != ios)
{
ios.close();
}
if (null != writer)
{
writer.dispose();
}
}
}
}