1. 程式人生 > >Java 自定義文字圖片

Java 自定義文字圖片

package com.study.util;


import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;


public class Test {


    public static void main(String[] args) throws IOException {
        byte[] data = graphicsGeneration("哈哈哈");


        OutputStream outputStream = new FileOutputStream("D:\\test.png");
        outputStream.write(data);
        outputStream.close();
    }


    public static byte[] graphicsGeneration(String name) {
        byte[] b = null;
        int fontSize = 60; // 字型大小
        int imageX = 60; // 字的x軸
        int imageY = 75; // 字的y軸
        int imageWidth = 300;// 圖片的寬度
        int imageHeight = 150;// 圖片的高度
        Font font = new Font("楷體", Font.CENTER_BASELINE, fontSize);


        BufferedImage result = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_4BYTE_ABGR);
        Graphics2D graphics = result.createGraphics();
        graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 0));
        graphics.fillRect(0, 0, imageWidth, imageHeight);// 填充整個螢幕
        graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 1));
        graphics.setColor(Color.BLACK);
        graphics.setFont(font);
        graphics.drawString(name, imageX, imageY);
        // 將簽名影象放入這個資料夾中去,並調整大小
        graphics.drawImage(result.getScaledInstance(result.getWidth(), result.getHeight(), Image.SCALE_SMOOTH), 0, 0, null);
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ImageIO.write(result, "png", out);
            b = out.toByteArray();
            out.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return b;
    }
}