java 生产文字图片边缘有锯齿状

时间:2023-02-10 12:17:41

java生产文字图片时如果文字边缘有锯齿状


可以添加

gd.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB); 

消除锯齿状

public static BufferedImage drawTranslucentStringPic(int width, int height, Integer fontHeight,String drawStr) { 
		
        try {  
            BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
            Graphics2D gd = buffImg.createGraphics();  
            //设置透明  start  
            buffImg = gd.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);  
            gd=buffImg.createGraphics();  
            //设置透明  end  
            gd.setFont(new Font("方正舒体", Font.PLAIN, fontHeight)); //设置字体  
            gd.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB); //消除锯齿状
            gd.setColor(Color.white); //设置颜色  
            //gd.drawRect(0, 0, width - 1, height - 1); //画边框  
            gd.drawString(drawStr, width/2-fontHeight*drawStr.length()/2,fontHeight); //输出文字(中文横向居中)  
            return buffImg;  
        } catch (Exception e) {  
            return null;  
        }  
    }  
完整工程