class SpringbootWatermarkApplicationTests {
public static void main(String[] args) {
SpringbootWatermarkApplicationTests springbootWatermarkApplicationTests = new SpringbootWatermarkApplicationTests();
String realPath = "C:/Users/Administrator/Desktop/ceshitupian";
String sourceImg = realPath+"/66.jpg";
String targetImg = realPath+"/66-11.jpg";;
String watermarkTime = "2021-10-21";
String watermarkAddress = "北京世纪城";
Color color = Color.RED;
try {
springbootWatermarkApplicationTests.addNewWatermark(sourceImg,targetImg,watermarkTime,watermarkAddress,color);
File image = new File(sourceImg);
String dest = realPath + "/suluetu.jpg";
springbootWatermarkApplicationTests.thumbnailImage(image, 50, 50, dest);
} catch (Exception e) {
e.printStackTrace();
}
}
public void addNewWatermark(String sourceImg, String targetImg, String watermarkTime, String watermarkAddress,
Color color) throws IOException {
File srcImgFile = new File(sourceImg);
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);
g.setColor(color);
int fontSize = srcImgWidth / 300 * 10;
Font font = new Font("04b_08", Font.PLAIN, fontSize);//字体
g.setFont(font);
//设置水印的坐标
int x = srcImgWidth ;
int y = srcImgHeight - fontSize;
g.drawString(watermarkAddress, 0, y); //加水印
int ys = srcImgHeight - 2 * fontSize;
g.drawString(watermarkTime, 0, ys); //加水印
g.dispose();
File sf = new File(targetImg);
ImageIO.write(bufImg, "jpg", sf);
System.out.println("添加水印完成");
}
public static void thumbnailImage(File imgFile, int w,int h,String dest)throws Exception{
// ImageIO 支持的图片类型 : [BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG, JPEG, WBMP, GIF, gif]
String suffix = null;
// 获取图片后缀
if(imgFile.getName().indexOf(".") > -1) {
suffix = imgFile.getName().substring(imgFile.getName().lastIndexOf(".") + 1);
}
Image img = ImageIO.read(imgFile);
// 根据原图与要求的缩略图比例,找到最合适的缩略图比例
int width = img.getWidth(null);
int height = img.getHeight(null);
if((width*1.0)/w < (height*1.0)/h){
if(width > w){
h = Integer.parseInt(new java.text.DecimalFormat("0").format(height * w/(width*1.0)));
}
} else {
if(height > h){
w = Integer.parseInt(new java.text.DecimalFormat("0").format(width * h/(height*1.0)));
}
}
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
g.drawImage(img, 0, 0, w, h, Color.LIGHT_GRAY, null);
g.dispose();
// 将图片保存在原目录并加上前缀
ImageIO.write(bi, suffix, new File(dest));
}
}