实际上有可能在不读取整个目标图像的情况下将一个区域(小100x100px)写入图像(250k x 250k px)吗?我的区域只有100px的正方形,我喜欢把它存储在一个巨大的Jpeg文件的特定位置。谢谢你的提示。在
这可能不是你想要的,但我正在添加答案,如果其他人需要解决方案。: -)
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...
}
对于像BMP这样的原始格式,您只需要知道写入到哪里。
但是JPEG是一种(有损)压缩格式。您必须使数据与压缩算法保持一致。所以在图像中间写一些东西需要算法支持这个。我不太了解JPEG的细节,但我不认为这是它的一个特性。