Java 实现图片上面添加文字

直接上代码

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.swing.*;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;

public class AddTextToImg {
public static void main(String[] args) {
        String filePath = "D:\\学习\\pro_qrcode.png";
        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();
        }

    }



}

 

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值