在图片上添加文字

本文实现在图片上添加文字,大家可以百度一下ImageIcon类,在这里就不多介绍了!
这是一个main方法测试:

package test;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;

import javax.swing.ImageIcon;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class imgAddWords {

    public static void main(String[] a) {
        String words = "学无止境";// 添加的文字
        Color color = Color.yellow;// 文字颜色
        imgAddWords.createStringMark("D://a.jpg", words, color, 10, "d://b.jpg");
    }
    public static boolean createStringMark(String filePath, String words, Color color, float qualNum, String outPath) {
        ImageIcon imgIcon = new ImageIcon(filePath);
        Image theImg = imgIcon.getImage();
        // 获取图片尺寸
        int width = theImg.getWidth(null) == -1 ? 200 : theImg.getWidth(null);// 宽
        int height = theImg.getHeight(null) == -1 ? 200 : theImg.getHeight(null);// 高
        BufferedImage bimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bimage.createGraphics();
        g.setColor(color);
        g.setBackground(Color.red);
        g.drawImage(theImg, 0, 0, null);// 第二个和第三个参数是截图用的
        g.setFont(new Font(null, Font.BOLD, 15)); // 字体、字型、字号
        g.drawString(words, 10, height / 4); // 第二个参数横坐标,三个参数纵坐标
        g.dispose();
        try {
            FileOutputStream out = new FileOutputStream(outPath); // 先用一个特定的输出文件名
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bimage);
            param.setQuality(qualNum, true);
            encoder.encode(bimage, param);
            out.close();
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}

可以直接复制上面的代码使用,重要的参数都有注释,希望能帮到你们!(不清楚的可以留言问我)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值