附件上传添加水印和不添加水印

package saas.xazysoft.basic.controller.resource;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.apache.tomcat.util.http.ResponseUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import saas.xazysoft.basic.common.ErrorMsg;
import saas.xazysoft.basic.response.BasicException;
import saas.xazysoft.basic.response.GlobalResponse;
import saas.xazysoft.basic.utils.CommonUtil;
import saas.xazysoft.basic.utils.DateFormatUtil;
import saas.xazysoft.basic.utils.FilePathUtil;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.List;

/**
 * 西安卓越软件开发技术有限公司
 * 功能:文件上传控制器
 * 创建时间:2020/3/23-14:52
 * 版本       开发者        日期         描述
 * V1.0.0  xie tenggang    2020/3/23      新建
 */
@Slf4j
@RestController
@RequestMapping(value = "api/file_upload/")
@Api(tags = "文件上传API", description = "文件上传API")
public class UploadController {

    /**
     * 单文件上传
     *
     * @param file 上传文件
     * @return 返回文件路径
     */
    @PostMapping(value = "v1/upload")
    @ApiOperation(value = "单文件上传(无水印)")
    public GlobalResponse upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return GlobalResponse.fail(ErrorMsg.FAIL.getCode(), "上传失败,请选择文件");
        }
        String oldFileName = file.getOriginalFilename();
        String[] strings = oldFileName.split("\\.");
        String fileType = strings[strings.length - 1];
        String newName = System.currentTimeMillis() + CommonUtil.getNoncestr(6) + "." + fileType;
        String fullName = FilePathUtil.addPath(fileType) + newName;
        File newFile = new File(fullName);
        log.info("文件路径::::" + "/" + newFile.getPath());
        try {
            file.transferTo(newFile);
            log.info("文件上传成功!");
            return GlobalResponse.success(newFile.getPath());
        } catch (IOException e) {
            log.error("文件上传失败!");
            throw new BasicException(e.hashCode(), e.getMessage());
        }
    }

    /**
     * 多文件上传
     *
     * @param request
     * @return
     */
    @PostMapping(value = "v1/multiUpload")
    @ApiOperation(value = "多文件上传(无水印)")
    public GlobalResponse multiUpload(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        if (files.size() <= 0) {
            return GlobalResponse.fail(ErrorMsg.FAIL.getCode(), "上传失败,请选择文件");
        }
        String filePath = "d://" + "usr" + File.separator + "java" + File.separator + "upload" + File.separator;
        MultipartFile file = null;
        for (int i = 0; i < files.size(); i++) {
            file = files.get(i);
            if (file.isEmpty()) {
                return GlobalResponse.fail(ErrorMsg.FAIL.getCode(), "上传第" + (i + 1) + "个文件失败!");
            }
            String newFileName = new SimpleDateFormat("yyyyMMddhhmmssSSS").format(new Date()) + "_" + file.getOriginalFilename();
            File newFile = new File(filePath + newFileName);
            if (!newFile.getParentFile().exists()) {
                newFile.getParentFile().mkdirs();
            }
            try {
                file.transferTo(newFile);
                log.info("第" + (i + 1) + "个文件上传成功!");
            } catch (IOException e) {
                log.error("第" + (i + 1) + "个文件上传失败!");
            }
        }
        return GlobalResponse.success();
    }

    /**
     * 单文件上传
     *
     * @param file 上传文件
     * @return 返回文件路径
     */
    @PostMapping(value = "v1/watermark")
    @ApiOperation(value = "单文件上传(返回带水印)")
    public GlobalResponse addWatermark(@RequestParam("file") MultipartFile file) throws Exception {
        // 原图位置, 输出图片位置, 水印文字颜色, 水印文字
        // 读取原图片信息
        Image srcImg = ImageIO.read(file.getInputStream());
        int srcImgWidth = srcImg.getWidth(null);
        int srcImgHeight = srcImg.getHeight(null);
        // 加水印
        BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
        //获取 Graphics2D 对象
        Graphics2D g = bufImg.createGraphics();
        //设置绘图区域
        g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
        //设置字体
        Font font = new Font("宋体", Font.PLAIN, 80);
        // 根据图片的背景设置水印颜色
        g.setColor(Color.red);
        g.setFont(font);
        String content = DateFormatUtil.DateToString(new Date());
        //获取文字长度
        int len = g.getFontMetrics(g.getFont()).charsWidth(content.toCharArray(), 0, content.length());
        int x = srcImgWidth - len - 100;
        int y = srcImgHeight - 100;
        g.drawString(content, x, y);
        g.dispose();
        // 输出图片
        String oldFileName = file.getOriginalFilename();
        String[] strings = oldFileName.split("\\.");
        String fileType = strings[strings.length - 1];
        String fileSrc = System.currentTimeMillis() + CommonUtil.getNoncestr(6) + "." + fileType;
        File waterFile = new File(FilePathUtil.addPath(fileType) + fileSrc);
        FileOutputStream outImgStream = new FileOutputStream(waterFile);
        ImageIO.write(bufImg, "png", outImgStream);
        outImgStream.flush();
        outImgStream.close();
        return GlobalResponse.success(waterFile.getPath());
    }
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值