java 图片中加文字

java 图片中加文字

第一个参数是需要更改的图片文件路径,word是需要加入的文字,targetPath是重新生成的文件存放地址,

正常文件生成时需要上传文件服务器,所以返回的是生成的文件新路径,上传文件服务器之后记得删除生成的文件,

BufferedImage是JDK中自带的包,但是打包时会报错,所以使用 ImageIO,但是要注意图片格式,不要弄错,否则会读不出来

public static String addFont(String filePath,String word,String targetPath){

try{

File file = new File(filePath);

if(!file.exists()){

return "";

}

InputStream is = new FileInputStream(filePath);

//BufferedImage bi = ImageIO.read(is);

//通过JPEG图象流创建JPEG数据流解码器

//JPEGImageDecoder jpegDecoder = JPEGCodec.createJPEGDecoder(is);

//解码当前JPEG数据流,返回BufferedImage对象

//BufferedImage buffImg = jpegDecoder.decodeAsBufferedImage();

BufferedImage buffImg = ImageIO.read(is);

//得到画笔对象

Graphics g = buffImg.getGraphics();

//设置文字颜色。

g.setColor(Color.WHITE);

//最后一个参数用来设置字体的大小

Font f = new Font("微软雅黑",Font.PLAIN,120);

g.setFont(f);

//60,160 表示这段文字在图片上的位置(x,y) .第一个是你设置的内容。

g.drawString(word,60,160);

g.dispose();

OutputStream os;

targetPath = targetPath + System.currentTimeMillis() + ".jpg";

File file1 = new File(targetPath);

if(!file1.exists()){

file1.createNewFile();

}

os = new FileOutputStream(targetPath);

ImageIO.write(buffImg, "jpg", os);

//en.encode(buffImg);

is.close();

os.close();

}catch (Exception e){

e.printStackTrace();

}

return targetPath;

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值