将区域(100x100px)写入大文件而不读取目标jpeg

时间:2014-06-03 09:06:34

标签: java image image-processing jpeg

实际上是否可以在不读取整个目标图像的情况下为图像(250k x 250k px)写入一个区域(小100x100px)?我的区域只有100像素的正方形,我喜欢把它存放在巨大的Jpeg中的某个位置。 谢谢你的提示, 杜林

2 个答案:

答案 0 :(得分:3)

这可能不是你想要的,但我正在添加答案,如果其他人需要解决方案。 : - )

ImageIO API支持将区域写入文件。但是,这种支持是特定于格式的,正如其他答案已经指出的那样,JPEG(和大多数其他压缩格式)不是这样的格式。

public void replacePixelsTest(BufferedImage replacement) throws IOException {
    // Should point to an existing image, in a format supported (not tested)
    File target = new File("path/to/file.tif");

    // Find writer, use suffix of existing file
    ImageWriter writer = ImageIO.getImageWritersBySuffix(FileUtils.suffix(target)).next(); 
    ImageWriteParam param = writer.getDefaultWriteParam();

    ImageOutputStream output = ImageIO.createImageOutputStream(target);
    writer.setOutput(output);

    // Test if the writer supports replacing pixels
    if (writer.canReplacePixels(0)) {
        // Set the region we want to replace
        writer.prepareReplacePixels(0, new Rectangle(0, 0, 100, 100));

        // Replacement image is clipped against region prepared above
        writer.replacePixels(replacement, param);

        // We're done updating the image
        writer.endReplacePixels();
    }
    else {
        // If the writer don't support it, we're out of luck...
    }

    output.close(); // You probably want this in a finally block, but it clutters the example...
}

答案 1 :(得分:1)

对于像BMP这样的原始格式,您只需要知道写入的位置。

但JPEG是一种(有损)压缩格式。您必须使数据与压缩算法保持一致。因此,将某些内容写入图像中间需要算法来支持这一点。我没有详细了解JPEG,但我不认为这是它的一个特征。