Java 将文字写入图片中


public static void main(String[] args) {
    String filePath = "F:\\手机\\CoolMarket\\d8ec4cf70bd61dabb666b1f9f49bb8b7.jpg";
    String outPath = "d:\\宋体.png";   //第一次加字
    String word2 = "d:\\word2.png";

    String webFilePath_word3 = "d:\\word3.png";

    drawTextInImg(filePath, "阿尔法蛋AI故事机-用爸爸妈妈的声音讲故事", outPath, 60, 755, "black", 24.0f);//在图片上加商品标题(简介)
    drawTextInImg(outPath, "¥3199", word2, 90, 870, "red", 45.0f);//在图片上加商品价格
    drawTextInImg(word2, "原价:3399", webFilePath_word3, 225, 865, "black", 20.0f);//在图片上加商品原价
    System.out.println("Hello World!");
}

public static void drawTextInImg(String filePath, String text, String outPath, int left_n, int top_n, String color, float fsize) {
    ImageIcon imgIcon = new ImageIcon(filePath);
    Image img = imgIcon.getImage();
    int width = img.getWidth(null);
    int height = img.getHeight(null);
    BufferedImage bimage = new BufferedImage(width, height,
            BufferedImage.TYPE_INT_RGB);

    Graphics2D g = bimage.createGraphics();

    int fontSize = (int) fsize;    //字体大小
    int rectX = left_n;
    int rectY = top_n;
    int rectWidth = text.length() * (fontSize + 30);
    int rectHeight = fontSize + 8;

    Font font = new Font("宋体", Font.BOLD, fontSize);   //定义字体
    g.setBackground(Color.white);
    g.drawImage(img, 0, 0, null);
    if ("black".equals(color)) {
        g.setPaint(Color.black);
    } else if ("red".equals(color)) {
        g.setPaint(Color.red);
    }
    g.setFont(font);
    //g.drawRect(left_n, top_n, rectWidth, rectHeight);
    g.drawString(text, rectX, top_n);
    g.dispose();

    try {
        FileOutputStream out = new FileOutputStream(outPath);
        ImageIO.write(bimage, "png", out);
        out.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

声明:冰醋酸|版权所有,违者必究|如未注明,均为原创|本网站采用BY-NC-SA协议进行授权

转载:转载请注明原文链接 - Java 将文字写入图片中


一切随缘