1. 程式人生 > 實用技巧 >生成個人章程式碼

生成個人章程式碼

public static void createImage2(String str, Font font, File outFile, Integer width, Integer height) throws Exception {
    // 建立圖片
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = (Graphics2D) image.getGraphics();
    g.setClip(0, 0, width, height);
    g.setColor(Color.WHITE);
    // 先用黑色填充整張圖片,也就是背景
    g.fillRect(0, 0, width, height);

    //透明
    image = g.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
    g.dispose();
    g = image.createGraphics();
    g.setColor(Color.red);

    //畫框框
    g.setColor(new Color(220, 240, 240));
    g.setStroke(new BasicStroke(3.0f));
    // 畫橫線
    g.setColor(Color.red);

    g.drawLine(0, 0, width, 0);
    g.drawLine(0, height, width, height);
    // 畫豎線
    g.setColor(Color.red);
    g.drawLine(0, 0, 0, height);
    g.drawLine(width, 0, width, height);

    // 設定畫筆字型
    g.setFont(font);
    /** 用於獲得垂直居中y */
    FontMetrics fm = g.getFontMetrics(font);
    int ascent = fm.getAscent();
    int descent = fm.getDescent();
    int left = str.length() * 30;
    int y = (height - (ascent + descent)) / 2 + ascent;
    int x = (width - left) / 2;
    // 畫出字串
    g.drawString(str, x, y);
    g.dispose();
    // 輸出png圖片
    ImageIO.write(image, "png", outFile);
}

  簡易的紅色框+文字生成圖片功能