Saving large images - Raster problem

邮差的信 提交于 2019-12-05 15:38:10

This PNGJ library can be useful to read/write huge images, because it does it sequentially, it only keeps a line in memory at a time. (I wrote it myself a while ago, because I had a similar need)

I just hacked an minimal working example for a ComponentImage, which takes an arbitrary JComponent and can be passed to ImageIO for writing. For brevity, only the "interesting" parts are included here:

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;

    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!