繁体   English   中英

将小图像合并为一张,而无需在内存中分配完整图像

[英]Merge small images into one without allocating full image in memory

我必须在java中制作一个并行图像处理脚本,想法是将图像分成任意大小的图块,处理它们并重新组装最终图像。

现在我已经创建了一个函数:

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 文件。 这意味着您可以在例如 256 像素 (10000 * 256) 的行中写入 10000x10000(宽 * 高)像素的图像。

通常这会将内存使用量降低到实际水平。

所有必需的类都可以在这里找到:

PngXxlWriter 是主类。 通过调用它的方法writeTileLine您可以向输出图像添加一个新行。

https://sourceforge.net/p/mobac/code/HEAD/tree/trunk/MOBAC/src/main/java/mobac/utilities/imageio/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM