Skip to content

Instantly share code, notes, and snippets.

@yinheli
Created September 24, 2015 17:33
Show Gist options
  • Save yinheli/7af9d9eefe542a5231f6 to your computer and use it in GitHub Desktop.
Save yinheli/7af9d9eefe542a5231f6 to your computer and use it in GitHub Desktop.
java 生成图片, 从资源文件加载字体, 并且抗锯齿
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
/**
* @author yinheli
*/
public class T {
public static void main(String[] args) throws Exception {
Font font = Font.createFont(Font.TRUETYPE_FONT, new File("Microsoft Yahei.ttf"))
.deriveFont(Font.BOLD, 60f);
GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(font);
BufferedImage image = new BufferedImage(500, 200, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = (Graphics2D) image.getGraphics();
// 抗锯齿
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.setColor(Color.WHITE);
g.fillRect(0, 0, image.getWidth(), image.getHeight());
g.setFont(font);
g.setColor(Color.BLACK);
g.drawString("中文", 100, 100);
g.dispose();
ImageIO.write(image, "PNG", new File("result.png"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment