将小图像合并为一个而不在内存中分配完整图像 [英] Merge small images into one without allocating full image in memory
问题描述
我必须用Java编写一个并行的图像处理脚本,其目的是将图像划分为任意大小的图块,对其进行处理,然后重新组装最终图像.
I've to make a parallel image processing script in java, the idea is to divide the images into tiles of any size, process them, and reassemble the final image.
现在我已经创建了一个函数:
For now i've created a function:
public static BufferedImage readImg (String path, int startx, int starty, int w, int h)
将图像的区域返回为BufferedImage,然后对其进行处理,并将该区域放置在最终图像的正确位置.
that returns the region of an image as BufferedImage, then i'll process it and i want to place that region in the correct position of the final image.
因此,我尝试制作一个函数writeImg,该函数使用replacePixels方法仅将正确的位置写入而不将整个图像加载到内存中:
So i've tried to make a function writeImg that uses replacePixels method to write just in the correct position without loading the whole image into memory:
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,我不知道该怎么做.
The problem is that canReplacePixels is always set as false, and i've no idea what should i use to do that.
图像可能很大,因此不可能将整个图像加载到内存中,因为这会导致OutOfMemory异常.
The images can be very big so it's impossible to load the whole image in memory as it will cause a OutOfMemory exception.
推荐答案
只要您可以使用24位PNG文件作为输出,我就可以为您提供可行的解决方案(在GPL许可下):
As long as you are fine with an 24 bit PNG file as output I have a working solution for you (under GPL license):
PngXxlWriter类允许逐行"编写PNG文件.这意味着您可以在10,000行中写出10000x10000(宽*高)像素的图像. 256像素(10000 * 256).
The class PngXxlWriter allows to write PNG files "line by line". That means that you can write an image of 10000x10000 (width * height) pixels in lines of e.g. 256 pixels (10000 * 256).
通常,这会将内存使用量降低到实用水平.
Usually this reduces the memory usage down to a level which is practically.
所有必需的类都可以在这里找到
All required classes can be found here:
PngXxlWriter是主要类.通过调用其方法writeTileLine
,您可以在输出图像中添加新行.
PngXxlWriter is the main class. By calling its method writeTileLine
you can add a new line to the output image.
https://sourceforge.net/p/mobac/code/HEAD/tree/trunk/MOBAC/src/main/java/mobac/utilities/imageio/
这篇关于将小图像合并为一个而不在内存中分配完整图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!