有图有真相,先上图:
代码:
import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import javax.imageio.ImageIO; public class PictureMaker { public static void main(String[] args) { final int W=200; final int H=160; BufferedImage img=new BufferedImage(W,H,BufferedImage.TYPE_INT_RGB); Graphics2D g2d=(Graphics2D)img.getGraphics(); // 填充矩形 g2d.setColor(Color.red); g2d.fillRect(0, 0, W, H); // 绘直线 g2d.setColor(Color.yellow); g2d.setStroke(new BasicStroke(2.0f)); g2d.drawLine(20, H/2+10, W-20, H/2+10); // 绘文字 g2d.setFont(new Font("宋体",Font.BOLD,24)); g2d.drawString("2022新年快乐",26, H/2); g2d.dispose();// g2d使命完成 try { // 输出到文件 ImageIO.write(img, "PNG", new FileOutputStream("c:\\hy\\1.PNG")); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
END