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());
}