我必须用java编写一个并行的图像处理脚本,这个想法是将图像分成任意大小的瓦片,对它们进行处理,然后重新组装最终的图像。
现在,我已经创建了一个函数:
public static BufferedImage readImg (String path, int startx, int starty, int w, int h)它以BufferedImage的形式返回图像的区域,然后我将对其进行处理,并希望将该区域放置在最终图像的正确位置。
因此,我尝试使用replacePixels方法创建一个函数writeImg,它只在正确的位置写入内容,而不会将整个图像加载到内存中:
public static void writeImg (String path, int startx, int starty, BufferedImage image){
File output = new File(path);
ImageOutputStream ios = null;
try {
ios = ImageIO.createImageOutputStream(output);
} catch (IOException e){
e.printStackTrace();
}
Iterator iter = ImageIO.getImageWritersByFormatName("JPEG");
ImageWriter writer = (ImageWriter)iter.next();
writer.setOutput(ios);
try{
if(writer.canReplacePixels(0)){
System.out.println("True");
}else{
System.out.println("False");
}
}catch (IOException e) {
e.printStackTrace();
}
ImageWriteParam param = writer.getDefaultWriteParam();
Point destinationOffset = new Point(startx,starty);
param.setDestinationOffset(destinationOffset);
try {
writer.replacePixels(image, param);
} catch (IOException e) {
e.printStackTrace();
}
}问题是canReplacePixels总是被设置为false,我不知道我应该用什么来做这件事。
图像可能非常大,因此不可能将整个图像加载到内存中,因为这将导致OutOfMemory异常。
发布于 2011-03-05 00:28:59
只要你能接受24位的PNG文件作为输出,我有一个可行的解决方案(在GPL许可下):
PngXxlWriter类允许“逐行”地编写PNG文件。这意味着你可以写一个10000x10000 (宽*高)像素的图像,比如256像素(10000 * 256)的线条。
通常情况下,这会将内存使用量降低到实际的水平。
所有需要的类都可以在这里找到:
PngXxlWriter是主类。通过调用它的方法writeTileLine,您可以在输出图像中添加新的一行。
https://sourceforge.net/p/mobac/code/HEAD/tree/trunk/MOBAC/src/main/java/mobac/utilities/imageio/
https://stackoverflow.com/questions/5196445
复制相似问题