图片上添加文字

public class ImageAddWord
{
public void addWord(String filePath, String watermark,String outpath, int x, int y,
String fontname, int fontsize, Color color)
{
// 根据图片路径将原图片装进ImageIcon对象中
ImageIcon imgIcon = new ImageIcon(filePath);
// 将原图片转换为Image
Image theImg = imgIcon.getImage();
// 根据图片路径将水印图片装进ImageIcon对象中
//ImageIcon waterIcon = new ImageIcon(watermark);
// 将水印图片转换为Image
//Image waterImg = waterIcon.getImage();
// 获取原图片的宽和高
int width = theImg.getWidth(null);
int height = theImg.getHeight(null);
// 创建BufferedImage对象
BufferedImage bimage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// 创建Graphics2D对象
Graphics2D g = bimage.createGraphics();
// g.setColor(Color.red);
// g.setFont(new Font("宋体",Font.BOLD,36));
// 设置字体样式
g.setColor(color);
g.setFont(new Font(fontname, Font.BOLD, fontsize));
g.setBackground(Color.white);
g.drawImage(theImg, 0, 0, null);
//图片比例
float m=(float)((double)width/480.0);
float n=(float)((double)height/360.0);
//System.out.print(k+","+h);

// 设置透明度
g.setComposite(AlphaComposite
.getInstance(AlphaComposite.SRC_OVER, 0.8f));
//g.drawImage(waterImg, 100, 100, null); // 添加水印图片
g.drawString(watermark, x*m,y*n+fontsize); // 添加文字
g.dispose();
// 图片画板创建结束后将图片以文件流写出到指定路径
try
{
FileOutputStream out = new FileOutputStream(outpath);
// 设置文件流格式
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
// 对图片进行编码处理
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bimage);
param.setQuality(1.0f, true); // 设置图片质量
encoder.encode(bimage, param);// 将BufferedImage对象中的文件生成图片
//encoder.encode(bimage);
out.close();
} catch (Exception e)
{
e.printStackTrace();
}

}

public static void main(String[] args)
{
ImageAddWord imageAddWord = new ImageAddWord();
String filepath="D://test522.jpg";
String outpath="D://test522.jpg";
imageAddWord
.addWord(
filepath,
"美女b",outpath, 60, 100, "宋体", 12, Color.green);
System.out.print("操作成功完成!");

}

版权声明:本文为博主原创文章,未经博主允许不得转载。

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值