/**
* 通用上传请求(单个)
*/
@PostMapping("/upload")
public AjaxResult uploadFile(MultipartFile file) throws Exception
{
try
{
// 上传文件路径
String filePath = RuoYiConfig.getUploadPath();
// 上传并返回新文件名称
String fileName = FileUploadUtils.upload(filePath, file);
String updatedFilePath = removePathBeforeSecondSlash(fileName);
// 添加水印
String watermarkFilePath = addWatermark(filePath + updatedFilePath);
String url = serverConfig.getUrl() + watermarkFilePath;
AjaxResult ajax = AjaxResult.success();
ajax.put("url", url);
ajax.put("fileName", fileName);
ajax.put("newFileName", FileUtils.getName(fileName));
ajax.put("originalFilename", file.getOriginalFilename());
return ajax;
}
catch (Exception e)
{
return AjaxResult.error(e.getMessage());
}
}
private String removePathBeforeSecondSlash(String filePath)
{
int count = 0;
int index = -1;
for (int i = 0; i < filePath.length(); i++) {
if (filePath.charAt(i) == '/') {
count++;
if (count == 3) {
index = i;
break;
}
}
}
if (index != -1) {
return filePath.substring(index);
}
return filePath;
}
private String addWatermark(String filePath) throws IOException
{
BufferedImage image = ImageIO.read(new File(filePath));
// 创建Graphics对象,并设置水印文字的样式
Graphics2D g2d = (Graphics2D) image.getGraphics();
Font font = new Font("微软雅黑", Font.BOLD, 20);
g2d.setFont(font);
Color watermarkColor = new Color(128, 128, 128, 128);
g2d.setColor(watermarkColor);
// 在右下角添加水印
String watermark = "水印名称";
int x = image.getWidth() - g2d.getFontMetrics().stringWidth(watermark) - 10;
int y = image.getHeight() - 10;
g2d.drawString(watermark, x, y);
// 保存添加水印后的图片,覆盖原始图片
File output = new File(filePath);
ImageIO.write(image, "jpg", output);
g2d.dispose();
return filePath;
}
水印被csdn 的水印所覆盖