File f = new File("XXXXXXXXXXX");//要加水印的图片
File mark = new File("/mark.png");//水印图片 为什么要定义两个呢下面说明
File mark2 = new File("/mark2.png");
//获取图片的宽度,得到缩放比例
BufferedImage image = ImageIO.read(f);
int imageWidth = image.getWidth();
float scale = imageWidth / 1024f;
//对水印进行缩放 这里mark2 就是保存缩放后的图片
ImageKit.compassImage(mark, mark2, (int) (scale * ImageIO.read(mark).getWidth()), (int) (ImageIO.read(mark).getHeight() * scale), "png"); //这里之所以会用到ImageKit对图片经行缩放是因为Thumbnails缩放后的图片如果原图是透明的话缩放后会变黑
//右下角加水印
Thumbnails.of(f).scale(1.0f).watermark(Positions.BOTTOM_RIGHT, ImageIO.read(mark2), 0.8f).outputQuality(1.0f).toFile(file);
下面是ImageKit的类
public class ImageKit {
private static ImageKit manager = new ImageKit();
public BufferedImage readImage(File file) {
BufferedImage image = null;
if (file != null && file.isFile() && file.exists()) {
try {
image = ImageIO.read(file);
} catch (IOException e) {
e.printStackTrace();
}
}
return image;
}
public double getWidth(BufferedImage image) {
return image.getWidth();
}
public double getHeight(BufferedImage image) {
return image.getHeight();
}
public BufferedImage zoom(BufferedImage image, int width, int heigth) {
ResampleOp resampleOp = new ResampleOp(width, heigth);
BufferedImage tag = resampleOp.filter(image, null);
return tag;
}
public double[] zoomSize(BufferedImage image, int width, int heigth) {
double[] zoomSize = new double[2];
double srcWidth = getWidth(image);
double srcHeigth = getHeight(image);
if (srcWidth > srcHeigth) {
zoomSize[0] = (srcWidth / srcHeigth) * heigth;
zoomSize[1] = heigth;
}
if (srcWidth < srcHeigth) {
zoomSize[0] = width;
zoomSize[1] = (srcHeigth / srcWidth) * width;
}
return zoomSize;
}
public void writeImage(BufferedImage image, String formatName, File file) throws IOException {
if (image != null && formatName != null && !"".equals(formatName) && file != null) {
ImageIO.write(image, formatName, file);
}
}
public static BufferedImage getCompassImage(String src, int w, int h) throws IOException {
BufferedImage image = manager.readImage(new File(src));
double[] size = manager.zoomSize(image, w, h);
return manager.zoom(image, (int) size[0], (int) size[1]);
}
public static void compassImage(File src, File to, int w, int h, String ext) throws IOException {
BufferedImage image = manager.readImage(src);
double[] size = manager.zoomSize(image, w, h);
manager.writeImage(manager.zoom(image, (int) size[0], (int) size[1]), ext, to);
}
public static void compassImage(String src, String to, int w, int h, String ext) throws IOException {
compassImage(new File(src), new File(to), w, h, ext);
}
public static String getFormatName(Object o) {
try {
ImageInputStream iis = ImageIO.createImageInputStream(o);
Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
if (!iter.hasNext()) {
return null;
}
ImageReader reader = iter.next();
iis.close();
return reader.getFormatName();
} catch (IOException e) {}
return null;
}
}