1

我的面板看起来像:

在此处输入图像描述

当我转换为图像

public BufferedImage createImage(JPanel panel) {

int w = (int) PageSize.A4.getWidth();//panel.getWidth();
int h = (int) PageSize.A4.getHeight();//panel.getHeight();

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);

BufferedImage resizedImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, w, h, null);
g.dispose();
g.setComposite(AlphaComposite.Src);

g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
        RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.setRenderingHint(RenderingHints.KEY_RENDERING,
        RenderingHints.VALUE_RENDER_QUALITY);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);

return resizedImage;
}

它看起来很糟糕 - 更大更差的质量

在此处输入图像描述

我如何将这个图像的质量更改为面板的质量?

编辑:

您需要编译此代码的库:

import com.itextpdf.text.PageSize;
import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
4

2 回答 2

1

您可以使用 Graphics2D 转换,以便面板的绘画立即转到缩放图像

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();

顺便说一句,setRenderingHint 在您处理完 Graphics 后不会做任何有用的事情

于 2012-04-28T19:27:45.057 回答
1

从字面上回答你的问题:

如何将此图像的质量更改为面板的质量?

很简单,不要改变图像的大小。放弃整个“将图像拉伸到 A4 尺寸”,因为这是质量损失的原因。

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;
}

但是不确定这是否是您一直在寻找的。如果您真的希望图像为 A4 尺寸,我建议您在将其转换为图像之前尝试让您的面板在 A4 尺寸上清晰呈现。将小图像拉伸到较大版本总是会导致质量损失。

于 2012-04-28T20:21:43.547 回答