java添加水印和oss图片加水印的两种方法

目录

java添加文字/图片水印并设置水印位置和旋转角度

阿里云oss方式一:图片的后缀拼接>官方文档<阿里云支持的方式,推荐

阿里云oss方式二:上传时加水印


java添加文字/图片水印并设置水印位置和旋转角度


import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;

import javax.imageio.ImageIO;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

@Slf4j
public class WaterUtil {

    /**
     * 把水印印刷到图片上
     *
     * @param pressImg  -- 水印文件
     * @param targetImg -- 目标文件
     * @param newImg    -- 新文件
     * @param loaction  水印位置:left-top:左上角,right-top:右上角,left-bottom:左下角,right-bottom:右下角
     * @param degree    水印旋转角度
     */
    public static void pressImage(String pressImg, String targetImg, String newImg, String loaction, Integer degree) {
        try {
            // 目标文件
            File _file = new File(targetImg);
            Image src = ImageIO.read(_file);
            int wideth = src.getWidth(null);
            int height = src.getHeight(null);
            BufferedImage image = new BufferedImage(wideth, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = image.createGraphics();
            g.drawImage(src, 0, 0, wideth, height, null);


            // 水印文件
            File _filebiao = new File(pressImg);
            Image src_biao = ImageIO.read(_filebiao);
            int wideth_biao = src_biao.getWidth(null);
            int height_biao = src_biao.getHeight(null);
            // 水印坐标
            int x = 0, y = 0;
            if (StringUtils.equals(loaction, "left-top")) {
                g.drawImage(src_biao, x, y, wideth_biao, height_biao, null);
            } else if (StringUtils.equals(loaction, "right-top")) {
                x = wideth - wideth_biao;
            } else if (StringUtils.equals(loaction, "left-bottom")) {
                y = height - height_biao;
            } else if (StringUtils.equals(loaction, "right-bottom")) {
                x = wideth - wideth_biao;
                y = height - height_biao;
            } else {
                x = (wideth - wideth_biao) / 2;
                y = (height - height_biao) / 2;
            }


            if (null != degree) {
                // 设置水印旋转
                g.rotate(Math.toRadians(degree), x, y);
            }
            g.drawImage(src_biao, x, y, wideth_biao, height_biao, null);
            // 水印文件结束
            g.dispose();
            FileOutputStream out = new FileOutputStream(newImg);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            encoder.encode(image);
            out.close();
        } catch (Exception e) {
            log.error("把水印印刷到图片上出错了" + e);
        }
    }


    /**
     * 打印文字水印图片
     *
     * @param fontStyle -- 字体
     * @param color     -- 字体颜色
     * @param fontSize  -- 字体大小
     * @param x         -- 偏移量x
     * @param y         -- 偏移量y
     * @param pressText --文字
     * @param targetImg -- 目标图片
     * @param fontName -- 字体名
     */
    public static void pressText(String pressText, String targetImg, String fontName, int fontStyle, int color,
                                 int fontSize, int x, int y) {
        try {
            File _file = new File(targetImg);
            Image src = ImageIO.read(_file);
            int wideth = src.getWidth(null);
            int height = src.getHeight(null);
            BufferedImage image = new BufferedImage(wideth, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = image.createGraphics();
            g.drawImage(src, 0, 0, wideth, height, null);

            g.setColor(Color.RED);
            g.setFont(new Font(fontName, fontStyle, fontSize));

            g.drawString(pressText, wideth - fontSize - x, height - fontSize / 2 - y);
            g.dispose();
            FileOutputStream out = new FileOutputStream(targetImg);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            encoder.encode(image);
            out.close();
        } catch (Exception e) {
            log.error("打印文字水印图片出错了" + e);
        }
    }

//    public static void main(String[] args) {
//        File fileDir = new File("C:/Users/as/Desktop/img-test");
//        File[] tempList = fileDir.listFiles();
//        System.out.println("该目录下对象个数:" + tempList.length);
//        for (File file : tempList) {
//            if (file.isFile()) {
//                pressImage("C:/Users/as/Desktop/img-test/shuiyin.png", file.getPath(), file.getPath(), "right-top", 0);
//            }
//        }
//    }

    public static void main(String[] args) {
//        pressImage("C:/Users/as/Desktop/img-test/shuiyin.png", "C:/Users/as/Desktop/img-test/1.jpg", "C:/Users/as/Desktop/img-test/1.jpg", "left-top", -45);
//        pressImage("C:/Users/as/Desktop/img-test/shuiyin.png", "C:/Users/as/Desktop/img-test/2.jpg", "C:/Users/as/Desktop/img-test/2.jpg", "right-top", -45);
//        pressImage("C:/Users/as/Desktop/img-test/shuiyin.png", "C:/Users/as/Desktop/img-test/3.jpg", "C:/Users/as/Desktop/img-test/3.jpg", "center", -145);
//        pressImage("C:/Users/as/Desktop/img-test/shuiyin.png", "C:/Users/as/Desktop/img-test/4.jpg", "C:/Users/as/Desktop/img-test/4.jpg", "left-bottom", -45);
//        pressImage("C:/Users/as/Desktop/img-test/shuiyin.png", "C:/Users/as/Desktop/img-test/5.jpg", "C:/Users/as/Desktop/img-test/5.jpg", "right-bottom",
//                -45);
        pressImage("D:/szw/photo/微信图片_20200911171947.png",
                "D:/szw/photo/微信图片_20200911171651.png",
                "D:/szw/photo/加水印后.png",
                "right-bottom",
                0);
    }

}

阿里云oss方式一:图片的后缀拼接>官方文档<阿里云支持的方式,推荐

详细参考:阿里云对象存储 OSS-图片水印

操作开始:

       

编码后的内容:ZmlsZS9zaHVpeWluLnBuZw

在需要加水印的图片路径后面加上“?x-oss-process=image/resize,w_300,h_300/quality,q_90/watermark,image_ZmlsZS9zaHVpeWluLnBuZw,t_90,g_se,x_10,y_10”

?x-oss-process=image/resize,w_300,h_300/quality,q_90/watermark,image_ZmlsZS9zaHVpeWluLnBuZw,t_90,g_se,x_10,y_10

 其他参数含义:

结束!是不是很简单

阿里云oss方式二:上传时加水印

 public String uploadImage(MultipartFile file,String sn){
        if(file==null|| StrUtil.isEmpty(sn)){
            return ApiResult.error("传入参数不能为空");
        }
            try (InputStream inputStream=file.getInputStream();
                 ByteArrayOutputStream os = new ByteArrayOutputStream();){

                //获取图片名称
               String fileName= file.getOriginalFilename();
                Image srcImg=ImageIO.read(inputStream);
                LocalDateTime now = LocalDateTime.now();
                // add by chenxin  start   给图片加上水印
                Font font = new Font("微软雅黑", Font.PLAIN, 100);                     //水印字体
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                String waterMarkContent = sdf.format(new Date());  //水印内容
                Color color = new Color(255, 255, 255, 255);
                if(srcImg!=null){
                    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, 1, 2, srcImgWidth, srcImgHeight, null);

                    g.setColor(color); //根据图片的背景设置水印颜色
                    g.setFont(font);              //设置字体
                    g.drawString(waterMarkContent, 100, 100);  //画出水印
                    g.dispose();
                    System.out.println("文件名称为:"+file.getOriginalFilename());
                    ImageIO.write(bufImg, "jpg", os);
                    bufImg.flush();
                    try (InputStream input=new ByteArrayInputStream(os.toByteArray())){

              //          String url = AliOssUtils.uploadFileToOssFileName(file,"device");
                        String url = AliOssUtils.uploadFileToOss(input, "device/"+sn, 1, fileName);
                    
                        return  url;
                    }
                }

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }//文件转化为图片
           catch (Exception e){
            log.info("上传图片失败{}",e.getMessage());
            return ApiResult.error("上传失败");
        }
            return null;

    }



public static String uploadFileToOss(InputStream inputStream,String upName,Integer water,String file) {
        // 创建OSSClient实例
        OSSClient ossClient = new OSSClient(OssConstant.endpoint, OssConstant.ALIYUN_SMS_ACCESS_KEY, OssConstant.ALIYUN_SMS_SECRET_KEY);
        try {
            String fileName = upName+"/"+file;
            ossClient.putObject(OssConstant.bucketName, OssConstant.AlIYUN_SMS_File_NAME + fileName, inputStream);
            String url = OssConstant.accesspoint + OssConstant.AlIYUN_SMS_File_NAME + fileName;
            return  url;

        } catch (OSSException oe) {
            log.info("Caught an OSSException, which means your request made it to OSS, \"\n" +
                    "                    + \"but was rejected with an error response for some reason.");
            log.info("Error Message:{},ErrorCode:{},Request:{},Host ID:{}",
                    oe.getErrorMessage(), oe.getErrorCode(), oe.getRequestId(), oe.getHostId());
            log.error(oe.getErrorCode() + oe.getErrorMessage());
            return  "error";
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message: " + ce.getMessage());
            log.error(ce.getErrorCode() + ce.getErrorMessage());
            return "error";
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            AliOssUtils.shutdown(ossClient);
        }
        return  "error";
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

瑶山

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值