我已经问了一个问题如何保存大图像,我觉得我走在正确的轨道上,但我还是需要一些建议。
我有一张Image 12000 x 12000,我需要将其另存为.png
无法使用BufferedImage。
我已经被建议使用RenderedImage接口,但不知怎的,我无法获得所需的结果。 (我还没有使用过栅格,所以我可能错了)
保存图片方法的代码:
public static void SavePanel() {
PanelImage IMAGE = new PanelImage(panel);
try {
ImageIO.write(IMAGE, "png", new File(ProjectNameTxt.getText() + ".png"));
} catch (IOException e) {
}
}
PanelImage类的代码:
public static class PanelImage implements RenderedImage {
// some variables here
public PanelImage(JImagePanel panel) {
this.panel = panel;
}
public Raster getData(Rectangle rect) {
sizex = (int) rect.getWidth();
sizey += (int) rect.getHeight();
image = null;
image = new BufferedImage(
(int) sizex,
(int) sizey,
BufferedImage.TYPE_INT_RGB);
g2 = image.createGraphics();
panel.paintComponent(g2);
return image.getData();
}
// rest of the implemented methods - no problems here
}
我注意到ImageIO一次请求一行像素(12000 x 1)。 这种方法有效但我仍然需要BufferedImage中的整个图像。 每次ImageIO调用方法时我都要增加BImage的大小,否则我会得到“Coordinate out of bounds!”exeption
由于
答案 0 :(得分:3)
这个PNGJ库可用于读/写大图像,因为它按顺序执行,它一次只在内存中保留一行。 (我刚才自己写了,因为我有类似的需要)
答案 1 :(得分:2)
我刚刚攻击了ComponentImage
的最小工作示例,它采用了任意JComponent
并可以传递给ImageIO
进行写入。为简洁起见,此处仅包含“有趣”部分:
public final class ComponentImage implements RenderedImage {
private final JComponent comp;
private final ColorModel colorModel;
private final SampleModel sampleModel;
public ComponentImage(JComponent comp) {
this.comp = comp;
this.colorModel = comp.getColorModel();
this.sampleModel = this.colorModel.createCompatibleWritableRaster(1, 1).
getSampleModel();
}
@Override
public ColorModel getColorModel() {
return this.comp.getColorModel();
}
@Override
public SampleModel getSampleModel() {
return this.sampleModel;
}
@Override
public Raster getData(Rectangle rect) {
final WritableRaster raster = this.colorModel.
createCompatibleWritableRaster(rect.width, rect.height);
final Raster result = raster.
createChild(0, 0, rect.width, rect.height,
rect.x, rect.y, null);
final BufferedImage img = new BufferedImage(
colorModel, raster, true, null);
final Graphics2D g2d = img.createGraphics();
g2d.translate(-rect.x, -rect.y);
this.comp.paintAll(g2d);
g2d.dispose();
return result;
}
}