我必须用java制作一个并行图像处理脚本,其想法是将图像划分为任意大小的图 block ,处理它们,然后重新组合最终图像。
现在我已经创建了一个函数:
public static BufferedImage readImg (String path, int startx, int starty, int w, int h)
将图像区域返回为 BufferedImage,然后我将对其进行处理,并希望将该区域放置在最终图像的正确位置。
所以我尝试创建一个 writeImg 函数,它使用 ReplacePixels 方法在正确的位置写入,而不将整个图像加载到内存中:
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 异常。
最佳答案
只要您愿意使用 24 位 PNG 文件作为输出,我就有一个适合您的可行解决方案(在 GPL 许可下):
PngXxlWriter 类允许“逐行”写入 PNG 文件。这意味着您可以在行中写入 10000x10000(宽度 * 高度)像素的图像,例如256 像素 (10000 * 256)。
通常这会将内存使用量降低到实际水平。
所有必需的类(class)都可以在这里找到:
PngXxlWriter 是主类。通过调用其方法writeTileLine
,您可以向输出图像添加新行。
https://sourceforge.net/p/mobac/code/HEAD/tree/trunk/MOBAC/src/main/java/mobac/utilities/imageio/
关于java - 将小图像合并为一张图像,而不在内存中分配完整图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5196445/