Bootstrap

java图片文字水印_Java实现图片添加水印文字(左右下角)

importjavax.imageio.ImageIO;import java.awt.*;importjava.awt.image.BufferedImage;importjava.io.File;importjava.io.FileOutputStream;/*** @ProjectName: test

* @Package: com.test.utils

* @ClassName: MyTest

* @Author: luqiming

* @Description:

* @Date: 2020/10/29 11:48

* @Version: 1.0*/

public classAddWatermarkUtil {public static voidwaterPress(String srcImgPath, String outImgPath,

Color markContentColor,intfontSize, String waterMarkContent) {try{

String[] waterMarkContents= waterMarkContent.split("\\|\\|");//读取原图片信息

File srcImgFile = newFile(srcImgPath);

Image srcImg=ImageIO.read(srcImgFile);int srcImgWidth = srcImg.getWidth(null);int srcImgHeight = srcImg.getHeight(null);//加水印

BufferedImage bufImg = newBufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);//得到画笔对象

Graphics2D g =bufImg.createGraphics();//设置起点

g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);

Font font= new Font("宋体", Font.PLAIN, fontSize);//根据图片的背景设置水印颜色

g.setColor(markContentColor);//设置水印文字字体

g.setFont(font);//数组长度

int contentLength =waterMarkContents.length;//获取水印文字中最长的

int maxLength = 0;for (int i = 0; i < contentLength; i++) {int fontlen =getWatermarkLength(waterMarkContents[i], g);if (maxLength

maxLength=fontlen;

}

}for (int j = 0; j < contentLength; j++) {

waterMarkContent=waterMarkContents[j];int tempX = 10;int tempY =fontSize;//单字符长度

int tempCharLen = 0;//单行字符总长度临时计算

int tempLineLen = 0;

StringBuffer sb= newStringBuffer();for (int i = 0; i < waterMarkContent.length(); i++) {char tempChar =waterMarkContent.charAt(i);

tempCharLen=getCharLen(tempChar, g);

tempLineLen+=tempCharLen;if (tempLineLen >=srcImgWidth) {//长度已经满一行,进行文字叠加

g.drawString(sb.toString(), tempX, tempY);//清空内容,重新追加

sb.delete(0, sb.length());

tempLineLen= 0;

}//追加字符

sb.append(tempChar);

}//通过设置后两个输入参数给水印定位

g.drawString(sb.toString(), 20, srcImgHeight - (contentLength - j - 1) * tempY-50);

}

g.dispose();//输出图片

FileOutputStream outImgStream = newFileOutputStream(outImgPath);

ImageIO.write(bufImg,"jpg", outImgStream);

outImgStream.flush();

outImgStream.close();

}catch(Exception e) {

e.printStackTrace();

}

}public static int getCharLen(charc, Graphics2D g) {returng.getFontMetrics(g.getFont()).charWidth(c);

}/*** 获取水印文字总长度

*

* @paramwaterMarkContent水印的文字

* @paramg

* @return水印文字总长度*/

public static intgetWatermarkLength(String waterMarkContent, Graphics2D g) {returng.getFontMetrics(g.getFont()).charsWidth(

waterMarkContent.toCharArray(),0, waterMarkContent.length());

}public static voidmain(String[] args) {//原图位置, 输出图片位置, 水印文字颜色, 水印文字

String font = "张天爱||就很完美||2020-05-27 17:00:00";

String inputAddress= "F:/UpupooWallpaper/1.jpg";

String outputAddress= "F:/UpupooWallpaper/1.jpg";

Color color=Color.GREEN;

waterPress(inputAddress, outputAddress, color,50, font);

}

}

悦读

道可道,非常道;名可名,非常名。 无名,天地之始,有名,万物之母。 故常无欲,以观其妙,常有欲,以观其徼。 此两者,同出而异名,同谓之玄,玄之又玄,众妙之门。

;