public Map uploadImg(MultipartFile file) throws IOException {
OutputStream os = null;
InputStream is = file.getInputStream();
try {
String path = "D:/testFile/";
byte[] bs = new byte[1024];
// 输出的文件流保存到本地文件
File tempFile = new File(path);
if (!tempFile.exists()) {
tempFile.mkdirs();
}
os = new FileOutputStream(tempFile.getPath() + File.separator + file.getOriginalFilename());
// 读取到的数据长度
int len;
// 开始读取
while ((len = is.read(bs)) > 0) {
os.write(bs, 0, len);
}
String urlPath = path + file.getOriginalFilename();
logger.info(urlPath);
Color markContentColor = new Color(234,17,92);
Font font = new Font("新宋体",Font.BOLD,30);
String waterMarkContent = "德玛西亚";
String tarImgPath = "D:/"+file.getOriginalFilename();
try {
// 读取原图片信息
File srcImgFile = new File(urlPath);
//文件转化为图片
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(markContentColor);
//设置字体
g.setFont(font);
//设置水印的坐标
int x1 = srcImgWidth - 2*getWatermarkLength(waterMarkContent, g);
int x = 380;
int y = 285;
int y1 = srcImgHeight - 2*getWatermarkLength(waterMarkContent, g);
g.drawString(waterMarkContent, x, y);
g.dispose();
// 输出图片
FileOutputStream outImgStream = new FileOutputStream(tarImgPath);
try {
ImageIO.write(bufImg, "png",outImgStream);
} catch (IOException e) {
e.printStackTrace();
}
logger.info("添加水印完成");
outImgStream.flush();
outImgStream.close();
} catch (Exception e) {
}
return null;
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 完毕,关闭所有链接
try {
os.close(); is.close();
} catch (IOException e) { e.printStackTrace(); }
} return null;}
public int getWatermarkLength(String waterMarkContent, Graphics2D g) {
return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
}