使用java实现文字叫水印,并且防止文字水印溢出图片
IMGIO详细了解
- 由于我们加水印是根据图片的像素值大小变化的, 我们需要去知道我们的图片像素,比如我们设置的文字像素是20,本来是有100个文字,
- 那么我们图片的像素就要是比两千像素大,但是图片是用户传的,我们控制不了呀,我们只能控制字体大小或者换行,那么如果文字有1000个
- 那么只有换行,因为缩小那样影响我们便于查看的意义.那么我这里是采取的换行实现不溢出的一个方法,大家可以参考一下哦.
public static void waterPress(File srcImgFile, Color markContentColor, String waterMarkContent) {
try {
String[] waterMarkContents = waterMarkContent.split("\\|\\|");
Image srcImg = ImageIO.read(srcImgFile);
int srcImgWidth = srcImg.getWidth(null);
int srcImgHeight = srcImg.getHeight(null);
BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bufImg.createGraphics();
g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
Font font = new Font("SimHei", Font.PLAIN, srcImg.getWidth(null) / 300 * 10);
g.setColor(markContentColor);
g.setFont(font);
float alpha = 0.5f;
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
int contentLength = waterMarkContents.length;
int watermarkIncreaseTheNumberOfLines = 0;
int maxLength = 0;
for (int i = 0; i < contentLength; i++) {
int fontlen = getWatermarkLength(waterMarkContents[i], g);
if (maxLength < fontlen) {
maxLength = fontlen;
}
}
Integer[] textLengths = new Integer[waterMarkContents.length];
for (int i = 0; i < contentLength; i++) {
int fontlen = getWatermarkLength(waterMarkContents[i], g);
textLengths[i] = fontlen;
}
int pixelSize = textLengths[0] / waterMarkContents[0].length();
for (Integer textLength :textLengths) {
if ((0.0 + textLength) / srcImgWidth > 1.0) {
int watermarkIncreaseTheNumberOfLines1 = textLength / (srcImgWidth - pixelSize);
watermarkIncreaseTheNumberOfLines += watermarkIncreaseTheNumberOfLines1;
}
}
int addition = 0;
for (int j = 0; j < contentLength; j++) {
waterMarkContent = waterMarkContents[j];
int tempX = 10;
int tempY = srcImg.getWidth(null) / 300 * 10;
int tempCharLen = 0;
int tempLineLen = 0;
StringBuffer sb = new StringBuffer();
for (int i = 0; i < waterMarkContent.length(); i++) {
char tempChar = waterMarkContent.charAt(i);
tempCharLen = getCharLen(tempChar, g);
tempLineLen += tempCharLen;
if (tempLineLen >= (srcImgWidth-pixelSize) || tempLineLen+(pixelSize*2) >= (srcImgWidth-pixelSize)) {
g.drawString(sb.toString(), tempY, srcImgHeight - ((contentLength+watermarkIncreaseTheNumberOfLines - (j+addition) - 1) * tempY + tempY));
addition +=1;
sb.delete(0, sb.length());
tempLineLen = 0;
}
sb.append(tempChar);
}
g.drawString(sb.toString(), tempY, srcImgHeight - ((contentLength+watermarkIncreaseTheNumberOfLines - (j+addition) - 1) * tempY + tempY));
}
g.dispose();
FileOutputStream outImgStream = new FileOutputStream(srcImgFile.getPath());
String suffix = srcImgFile.getPath().substring(srcImgFile.getPath().lastIndexOf(".")).substring(1);
ImageIO.write(bufImg, suffix, outImgStream);
outImgStream.flush();
outImgStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
