Java中为图片添加水印效果的方法——实例代码

时间:2022-04-29
本文章向大家介绍Java中为图片添加水印效果的方法——实例代码,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

直接写出代码:

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.font.TextAttribute;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import com.haohaosh.common.util.regex.RegexUtil;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
/**
*
* @项目名 ssh
* @功能 为图片添加水印效果
* @类名 ImageWaterMark
* @作者 Java自学通
* @日期 Aug 30, 20113:27:33 PM
* @版本 1.0
*/
public class ImageWaterMark {
private static final String HEAD = "好好生活网";
private static final String END = "www.haohaosh.com";
// 生成水印文件调用的方�?
private ImageWaterMark() {
}
/**
* 得到网站默认水印的缓存图�?
*
* @param image
* 图片
* @param fontType
* 字体
* @param apha
* 背景透明�?
* @param apha1
* 前景透明�?
* @return 缓存图片
*/
private static BufferedImage getMarkBufferedImage(Image image,
String fontType, float apha, float apha1) {
int width = image.getWidth(null);
int height = image.getHeight(null);
int fontSize = width / 15;
BufferedImage bimage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Font f = new Font(fontType, Font.PLAIN, fontSize);
Graphics2D g = bimage.createGraphics();
g.drawImage(image, 0, 0, null);
g.setFont(f);
AttributedString ats = new AttributedString(HEAD);
ats.addAttribute(TextAttribute.FONT, f, 0, HEAD.length());
AttributedCharacterIterator iter = ats.getIterator();
FontMetrics fm = g.getFontMetrics();
AttributedString ats1 = new AttributedString(END);
ats1.addAttribute(TextAttribute.FONT, f, 0, END.length());
AttributedCharacterIterator iter1 = ats1.getIterator();
FontMetrics fm1 = g.getFontMetrics();
int size = fm.stringWidth(HEAD);
int size1 = fm1.stringWidth(END) + 2;
g.setColor(Color.black);
g.setComposite(AlphaComposite
.getInstance(AlphaComposite.SRC_OVER, apha));
g.fill3DRect(0, 0, width, fontSize * 2 + 2, true);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
apha1));
g.setColor(Color.white);
int center = ((width - size) - (width - size1)) / 2;
g.drawString(iter, width - (size + center), fontSize);
g.drawString(iter1, width - size1, fontSize * 2);
g.dispose();
return bimage;
}
/**
* 根据水印内容、显示位置得到缓存图�?
*
* @param image
* 图片
* @param fontType
* 字体
* @param content
* 水印内容
* @param apha
* 背景透明�?
* @param apha1
* 前景透明�?
* @param fontSize
* 字体大小
* @param postion
* 位置
* @return 缓存图片
*/
public static BufferedImage getMarkBufferedImage(Image image,
String fontType, String content, float apha, float apha1,
int fontSize, Direction postion) {
int width = image.getWidth(null);
int height = image.getHeight(null);
BufferedImage bimage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g = bimage.createGraphics();
g.drawImage(image, 0, 0, null);
AttributedString ats = null;
AttributedCharacterIterator iter = null;
FontMetrics fm = null;
Font f = null;
int size = 0;
do {
f = new Font(fontType, Font.PLAIN, fontSize);
g.setFont(f);
ats = new AttributedString(content);
ats.addAttribute(TextAttribute.FONT, f, 0, content.length());
iter = ats.getIterator();
fm = g.getFontMetrics();
size = fm.stringWidth(content);
fontSize--;
} while (size > width && fontSize > 0);
fontSize++;
int x = 2, y = fontSize + fontSize / 2, h = 0;
if (postion == Direction.LEFT) {
h = height / 2 - (fontSize * 2 + 2) / 2;
y = height / 2 + fontSize / 2 - 2;
} else if (postion == Direction.RIGHT) {
h = height / 2 - (fontSize * 2 + 2) / 2;
y = height / 2 + fontSize / 2 - 2;
x = width - size;
} else if (postion == Direction.RIGHT_BOTTOM) {
h = height - (fontSize * 2 + 2);
x = width - size;
y = height - fontSize / 2 - 2;
} else if (postion == Direction.CONTENT) {
h = height / 2 - (fontSize * 2 + 2) / 2;
y = height / 2 + fontSize / 2 - 2;
x = width / 2 - size / 2;
} else if (postion == Direction.LEFT_BOTTOM) {
h = height - (fontSize * 2 + 2);
y = height - fontSize / 2 - 2;
} else if (postion == Direction.RIGHT_TOP) {
x = width - size;
} else if (postion == Direction.BOTTOM_CENTER) {
h = height - (fontSize * 2 + 2);
x = width / 2 - size / 2;
y = height - fontSize / 2 - 2;
} else if (postion == Direction.TOP_CENTER) {
x = width / 2 - size / 2;
}
g.setColor(Color.black);
g.setComposite(AlphaComposite
.getInstance(AlphaComposite.SRC_OVER, apha));
g.fill3DRect(0, h, width, fontSize * 2 + 2, true);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
apha1));
g.setColor(Color.white);
g.drawString(iter, x, y);
g.dispose();
return bimage;
}
/**
* 根据图片、内容�?�输出流输出加水印后的图�?
*
* @param img
* 图片
* @param content
* 水印文字
* @param stream
* 输出�?
*
*/
public static void outPutWebImageString(Image img, String content,
OutputStream stream) {
outPutWebImageString(img, content, stream, 0.3f, 1.0f, 16, "隶书");
}
/**
* 创建水印图片保存到输出流�?
*
* @param img
* @param content
* @param stream
* @param aph
* @param aph1
* @param fontSize
* @param font
*/
public static void outPutWebImageString(Image img, String content,
OutputStream stream, float aph, float aph1, int fontSize,
String font) {
writeImage(getMarkBufferedImage(img, font, content, aph, aph1,
fontSize, Direction.BOTTOM_CENTER), stream, null);
}
public static void outPutWebImageString(String content,
OutputStream stream, String filePath, float aph, float aph1,
int fontSize, String font) {
File file = new File(filePath);
if (file.isFile()) {
ImageIcon imgIcon = new ImageIcon(file.getAbsolutePath());
outPutWebImageString(imgIcon.getImage(), content, stream, aph,
aph1, fontSize, font);
}
}
public static void outPutWebImage(OutputStream stream, String filePath) {
outPutWebImage(stream, filePath, "时尚中黑�?�?", 0.3f, 0.7f);
}
public static void outPutWebImage(OutputStream stream, String filePath,
String font, float aph, float aph1) {
File file = new File(filePath);
if (file.isFile()) {
ImageIcon imgIcon = new ImageIcon(file.getAbsolutePath());
writeImage(
getMarkBufferedImage(imgIcon.getImage(), font, aph, aph1),
stream, filePath);
}
}
/**
* 根据路径生成水印图片保存到相对应目录(_back)
*
* @param path
*/
public static void execute(String path) {
File file = new File(path);
// 目标目录
StringBuffer targetDir = new StringBuffer();
if (file.isDirectory()) {
targetDir.append(file.getAbsolutePath()).append("_back");
writeImage(file.listFiles(), targetDir);
} else if (file.isFile()) {
ImageIcon imgIcon = new ImageIcon(file.getAbsolutePath());
writeImage(getMarkBufferedImage(imgIcon.getImage(), "时尚中黑�?�?",
0.3f, 0.7f), file.getParentFile().getAbsolutePath()
+ File.separator + "back_" + file.getName());
}
}
// �?查文件格�?
private static boolean checkFile(String path) {
Pattern pt = Pattern.compile("(.jpg)|(.jpeg)",
Pattern.CASE_INSENSITIVE);
Matcher mc = pt.matcher(path);
return mc.find();
}
private static void writeImage(File[] files, StringBuffer targetDir) {
File temp = new File(targetDir.toString());
if (!temp.exists())
temp.mkdirs();
for (File file : files) {
if (file.isDirectory()) {
targetDir.append("/").append(file.getName());
writeImage(file.listFiles(), targetDir);
} else if (checkFile(file.getName())) {
ImageIcon imgIcon = new ImageIcon(file.getAbsolutePath());
writeImage(getMarkBufferedImage(imgIcon.getImage(), "时尚中黑体",
0.3f, 0.7f), temp.getAbsolutePath() + File.separator
+ file.getName());
}
}
}
private static boolean writeImage(BufferedImage im, String filePath) {
FileOutputStream out = null;
try {
out = new FileOutputStream(filePath);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(im);
param.setQuality(50f, true);
encoder.encode(im, param);
out.flush();
} catch (Exception e) {
return false;
} finally {
try {
if (out != null) {
out.close();
out = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
private static void writeImage(BufferedImage im, OutputStream stream,
String filePath) {
try {
String temp = RegexUtil.getContentByRegex(filePath,
"(.+?)(.)(.+)", 3);
;
if (temp == null)
ImageIO.write(im, "JPEG", stream);
else
ImageIO.write(im, temp, stream);
} catch (Exception e) {
} finally {
try {
if (stream != null) {
stream.close();
stream = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}