java Graphics2D绘制文字并居中并解决服务器乱码问题

package com.test.testImage;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class Graphics2DTest {
    public static void main(String[] args) {   
        try {  
            String text = "文字居中";
            int width = 500;  
            int height = 400;  
            // 创建BufferedImage对象  
            BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);  
            // 获取Graphics2D  
            Graphics2D g2d = image.createGraphics();  
            // 画图  
            g2d.setBackground(new Color(255,255,255));  
            //g2d.setPaint(new Color(0,0,0));  
            g2d.setColor(Color.red);
            g2d.clearRect(0, 0, width, height);  
            Font font=new Font("宋体",Font.PLAIN,64);  
            g2d.setFont(font);  
            // 抗锯齿
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            // 计算文字长度,计算居中的x点坐标
            FontMetrics fm = g2d.getFontMetrics(font);
            int textWidth = fm.stringWidth(text);
            int widthX = (width - textWidth) / 2;
            // 表示这段文字在图片上的位置(x,y) .第一个是你设置的内容。
            g2d.drawString(text,widthX,100);  
            // 释放对象  
            g2d.dispose();  
            // 保存文件      
            ImageIO.write(image, "jpg", new File("D:/test.jpg"));  
        }  
        catch(Exception ex) {  
            ex.printStackTrace();  
        }   
    }   
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

微笑点燃希望

你的鼓励是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值