Created
September 24, 2015 17:33
-
-
Save yinheli/7af9d9eefe542a5231f6 to your computer and use it in GitHub Desktop.
java 生成图片, 从资源文件加载字体, 并且抗锯齿
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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