How to convert java swing panel to quality image

半城伤御伤魂 提交于 2019-12-06 20:54:33

To literally answer your question:

how I can change quality of this image to the quality of panel ?

Simple, do not alter the size of your image. Drop the whole 'stretching your image to A4 size' as this is the cause of the quality loss.

public BufferedImage createImage(JPanel panel) {
  BufferedImage originalImage = new BufferedImage(
        panel.getHeight(), panel.getWidth(), 
        BufferedImage.TYPE_BYTE_INDEXED);
  Graphics2D gg = originalImage.createGraphics();
  gg.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
        RenderingHints.VALUE_INTERPOLATION_BILINEAR);
  gg.setRenderingHint(RenderingHints.KEY_RENDERING,
        RenderingHints.VALUE_RENDER_QUALITY);
  gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);
  panel.paint(gg);
  gg.dispose();
  return originalImage;
}

Not sure however if this is what you have been looking for. If you really want the image to be on A4 size, I suggest trying to get your panel sharply rendered on A4 size before converting it to an image. Stretching a small image to a larger version will always result in quality loss.

you can use the Graphics2D transform so the panel's paint immediately goes to the scaled image

BufferedImage resizedImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g = resizedImage.createGraphics();
g.transform(AffineTransform.getScaleInstance((float)panel.getWidth()/w,
          (float)panel.getHeight()/h));//this might need to be inverted I'm not sure...
panel.paint(g);
g.dispose();

btw the setRenderingHint won't do anything useful after you disposed the Graphics

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