图片上添加文字

  1. public class ImageAddWord
  2. {
  3.  public void addWord(String filePath, String watermark,String outpath, int x, int y,
  4.    String fontname, int fontsize, Color color)
  5.  {
  6.   // 根据图片路径将原图片装进ImageIcon对象中
  7.   ImageIcon imgIcon = new ImageIcon(filePath);
  8.   // 将原图片转换为Image
  9.   Image theImg = imgIcon.getImage();
  10.   // 根据图片路径将水印图片装进ImageIcon对象中
  11.   //ImageIcon waterIcon = new ImageIcon(watermark);
  12.   // 将水印图片转换为Image
  13.   //Image waterImg = waterIcon.getImage();
  14.   // 获取原图片的宽和高
  15.   int width = theImg.getWidth(null);
  16.   int height = theImg.getHeight(null);
  17.   // 创建BufferedImage对象
  18.   BufferedImage bimage = new BufferedImage(width, height,
  19.     BufferedImage.TYPE_INT_RGB);
  20.   // 创建Graphics2D对象
  21.   Graphics2D g = bimage.createGraphics();
  22.   // g.setColor(Color.red);
  23.   // g.setFont(new Font("宋体",Font.BOLD,36));
  24.   // 设置字体样式
  25.   g.setColor(color);
  26.   g.setFont(new Font(fontname, Font.BOLD, fontsize));
  27.   g.setBackground(Color.white);
  28.   g.drawImage(theImg, 00null);
  29.   //图片比例
  30.   float m=(float)((double)width/480.0);
  31.   float n=(float)((double)height/360.0);
  32.   //System.out.print(k+","+h);
  33.   // 设置透明度
  34.   g.setComposite(AlphaComposite
  35.     .getInstance(AlphaComposite.SRC_OVER, 0.8f));
  36.   //g.drawImage(waterImg, 100, 100, null); // 添加水印图片
  37.   g.drawString(watermark, x*m,y*n+fontsize); // 添加文字
  38.   g.dispose();
  39.   // 图片画板创建结束后将图片以文件流写出到指定路径
  40.   try
  41.   {
  42.    FileOutputStream out = new FileOutputStream(outpath);
  43.    // 设置文件流格式
  44.    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
  45.    // 对图片进行编码处理
  46.    JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bimage);
  47.    param.setQuality(1.0f, true); // 设置图片质量
  48.    encoder.encode(bimage, param);// 将BufferedImage对象中的文件生成图片
  49. //   encoder.encode(bimage);
  50.    out.close();
  51.   } catch (Exception e)
  52.   {
  53.    e.printStackTrace();
  54.   }
  55.  }
  56.  public static void main(String[] args)
  57.  {
  58.   ImageAddWord imageAddWord = new ImageAddWord();
  59.   String filepath="D://test522.jpg";
  60.   String outpath="D://test522.jpg";
  61.   imageAddWord
  62.     .addWord(
  63.       filepath,
  64.       "美女b",outpath, 60100"宋体"12, Color.green);
  65.   System.out.print("操作成功完成!");
  66.  }
 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值