Java使用Graphics2D实现将网络图片转换到本地在为图片添加水印然后上传到腾讯云

使用Graphics2D实现将网络图片转换到本地在为图片添加水印然后上传到腾讯云

功能目标

:实现使用URL或者本地的图片添加水印

实现思路

:将URL文件转为流文件 在使用Graphics2D 为流文件添加水印,再将添加完水印的图片保存到本地,在根据保存在本地的水印图片上传到腾讯云

实现效果图:
Alt

代码实现

	/**
	* 测试函数
	**/
    public static void main(String[] args) {
        markImageByText("哈哈哈 @少年","网络图片的URL",null);
    }

    /**
     * 给图片添加水印文字
     *
     * @param logoText
     *            水印文字
     * @param srcImgPath
     *            源图片URL路径
     * @param targerPath
     *            添加完水印后保存到本地的路径
     */
    public static String markImageByText(String logoText, String srcImgPath, String targerPath) {
        return markImageByText(logoText, srcImgPath, targerPath, null);
    }

	/**
     * 给图片添加水印文字
     *
     * @param logoText
     * @param srcImgPath
     * @param targerPath
     * @param degree
     */
    public static String markImageByText(String logoText, String srcImgPath, String targerPath, Integer degree) {

        InputStream is = null;
        OutputStream os = null;
        String path = "";
        try {
            // 1、源图片
            URL file = new URL(srcImgPath);
            Image srcImg = ImageIO.read(file);
            BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null), srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);

            // 2、得到画笔对象
            Graphics2D g = buffImg.createGraphics();
            // 3、设置对线段的锯齿状边缘处理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null),
                    srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);
            // 4、设置水印旋转
            if (null != degree) {
                g.rotate(Math.toRadians(degree), (double) buffImg.getWidth() / 2, (double) buffImg.getHeight() / 2);
            }
            int width = buffImg.getWidth();
            int height = buffImg.getHeight();
            int length = logoText.length();
            // 设置水印在X轴的位置
            int a = width - (width - length);
            // 设置水印在Y轴的位置
            int b = height - 25;
            // 设置水印文字的大小
            int le = (width / length)/3;
            // 5、设置水印文字颜色
            g.setColor(color);
            // 文字边缘平滑
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            // 图片边缘平滑
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            // 6、设置水印文字Font
            Font font = new Font("宋体", Font.BOLD, le);
            g.setFont(font);
            // 7、设置水印文字透明度
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
            // 8、第一参数->设置的内容,后面两个参数->文字在图片上的坐标位置(x,y)
            g.drawString(logoText, a, b);
            // 9、释放资源
            g.dispose();
            // 10、生成图片
            File file2 = new File(srcImgPath);
            //创建目录 判断是否存在 不存在则创建
//            String filePath = "/var/data/image/"; // 这个是服务器的地址
            String filePath = "/Users/tp/var/data/image/"; // 这个是Mac本地的地址 win系统的可以自己更换地址 win格式地址
            File dir = new File(filePath);
            boolean mkdirs = false;
            // 判断地址是否存在。不存在则创建 需要注意的是 Mac创建的目录需要在二级目录 就好像/Users/tp/下才可以创建 所以你需要先有一个二级目录。如果直接在/Users/下创建 程序会报false 这个本人也没有去研究为什么
            if (!dir.exists() && !dir.isDirectory()) {
                mkdirs = dir.mkdirs();
                System.out.println(mkdirs);
                if (mkdirs == false){
                    return "";
                }
            }
            
            // 将流放到指定的目录
            String fileName = System.currentTimeMillis() + file2.getName();
            os = new FileOutputStream(filePath+fileName);
            // 将生成图片水印的流文件输出到你的本地 复制
            ImageIO.write(buffImg, "JPG",os);
            System.out.println("图片完成添加水印文字");
            // 将指定目录的文件上传至腾讯云
            System.out.println("图片上传到腾讯云");
            File file3 = new File(filePath+fileName);
            String key = file3.getName();
            PutObjectRequest putObjectRequest = new PutObjectRequest("腾讯云的桶名称", key, file3);
            COSCredentials cred = new BasicCOSCredentials("你在腾讯云注册获取的SecretId", "你在腾讯云注册获取的SecretKey");
            // 初始化
            ClientConfig clientConfig = new ClientConfig(new Region("ap-shanghai"));
            // 生成客户端
            COSClient cosClient = new COSClient(cred, clientConfig);
            cosClient.putObject(putObjectRequest);
            Date expiration = new Date(System.currentTimeMillis() + 5 * 60 * 10000);
            GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest("腾讯云的桶名称", key, HttpMethodName.GET);
            req.setExpiration(expiration);
            URL url = cosClient.generatePresignedUrl(req);
            // 返回上传图片的url访问地址
            path = url.getProtocol() + "://" + url.getHost() + url.getPath();
            // 删除本地水印图片
            File file4 = new File(filePath+fileName);
            if(file4.isFile()&&file4.exists()){
                file4.delete();
            }
            cosClient.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != is){
                    is.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if (null != os){
                    os.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return path;
    }


ps:一个开发界的小学生,一直在学习从未敢停止

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

TianYuuuuuuuuuuu

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

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

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

打赏作者

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

抵扣说明:

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

余额充值