java图片加文字

package com.cw.utils;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.font.TextAttribute;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;

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 d {

public static void main(String[] a) {

   d.createMark("c://aa.jpg", "c://bb.jpg", "djms179234", null, 1, "", 30);
   // System.out.println(d.createMark("e8.jpg","e81.jpg","",null,
   // 1,"",16));
}

/**

* @param souchFilePath:源图片路径
* @param targetFilePath:生成后的目标图片路径
* @param markContent:要加的文字
* @param markContentColor:文字颜色
* @param qualNum:质量数字
* @param fontType:字体类型
* @param fontSize:字体大小
* @return
*/
public static void createMark(String souchFilePath, String targetFilePath,
    String markContent, Color markContentColor, float qualNum,
    String fontType, int fontSize) {
  
   markContentColor = Color.red;
   ImageIcon imgIcon = new ImageIcon(souchFilePath);
   Image theImg = imgIcon.getImage();
   // Image可以获得 输入图片的信息
   int width = theImg.getWidth(null);
   int height = theImg.getHeight(null);

   // 800 800 为画出图片的大小
   BufferedImage bimage = new BufferedImage(width, height,
     BufferedImage.TYPE_INT_RGB);
   // 2d 画笔
   Graphics2D g = bimage.createGraphics();
   g.setColor(markContentColor);
   g.setBackground(Color.white);

   // 画出图片-----------------------------------
   g.drawImage(theImg, 0, 0, null);
   // 画出图片-----------------------------------

   // --------对要显示的文字进行处理--------------
   AttributedString ats = new AttributedString(markContent);
   Font f = new Font(fontType, Font.BOLD, fontSize);
   ats.addAttribute(TextAttribute.FONT, f, 0, markContent.length());
   AttributedCharacterIterator iter = ats.getIterator();
   // ----------------------

   g.drawString(iter, width-200,
     height - 30);
   // 添加水印的文字和设置水印文字出现的内容 ----位置
   g.dispose();// 画笔结束
   try {
    // 输出 文件 到指定的路径
    FileOutputStream out = new FileOutputStream(targetFilePath);
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);

    JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bimage);

    param.setQuality(qualNum, true);
    encoder.encode(bimage, param);
    out.close();
   } catch (Exception e) {
    e.printStackTrace();
   }
}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值