我正在使用最新的JDK 7u45进行开发。当我创建一个用于生成验证码的简单servlet时,我发现图像相当模糊。图像看起来像这样:
我的Macbook pro视网膜显示器的图像质量很差,看起来很差。 我用来创建BufferedImage的代码非常简单:
public static BufferedImage getImage() {
BufferedImage image = new BufferedImage(IMAGE_WIDTH,IMAGE_HEIGHT,BufferedImage.TYPE_INT_RGB);
Graphics graphics = image.getGraphics();
drawRandomNumber((Graphics2D)graphics);
return image;
}
private static void drawRandomNumber(Graphics2D graphics) {
graphics.setColor(Color.RED);
graphics.setFont(new Font("Arial",Font.BOLD|Font.ITALIC,RANDOM_NUMBER_FONT_SIZE));
char lch = 'a',hch = 'z';
char lcach = 'A',hcach = 'Z';
int x = RANDOM_NUMBER_START_X;
for (int i = 0;i < RANDOM_NUMBER_NUM;i++) {
char ch = new Random().nextBoolean() ?
(char)(new Random().nextInt(hch - lch) + lch) :
(char)(new Random().nextInt(hcach - lcach) + lcach);
int degree = new Random().nextInt() % 30;
graphics.rotate(degree * Math.PI / 180,x,RANDOM_NUMBER_START_Y);
graphics.drawString(ch + "",x,RANDOM_NUMBER_START_Y);
graphics.rotate(-degree * Math.PI / 180,x,RANDOM_NUMBER_START_Y);
x += 60;
}
}
将图像写入servlet的代码:
ImageIO.write(image, "png", response.getOutputStream());
我只是想知道如果我想创建一个支持HDPI显示的高质量图像,我该怎么办?有没有办法用java代码生成高质量的图像?我尝试了很多方法,但它们似乎没什么帮助
答案 0 :(得分:0)
private float xScaleFactor, yScaleFactor = ...;
private BufferedImage originalImage = ...;
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
int newW = (int)(originalImage.getWidth() * xScaleFactor);
int newH = (int)(originalImage.getHeight() * yScaleFactor);
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(originalImage, 0, 0, newW, newH, null);
}