您的位置:首页 > 编程语言 > Java开发

java实现图片水印添加

2018-11-08 14:15 253 查看

思路:

      1、获取到照片的文件流或者二进制数据

       2、通过bufferedimage 获取到一个画布

      3、获取到绘制工具Graphics2D

      4、将获取的Image写入画布

      5、工具设置字体、颜色以及旋转角度(以画布的中心点为基准进行旋转)

      6、循环写入要添加的字符水印  

详细代码如下

//将当前照片大小进行重置
    public static BufferedImage resizeImage(Image srcImage, int width, int height) {
        try {
            BufferedImage buffImg = null;
            buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
           // Graphics g=buffImg.getGraphics();
           // g.drawImage(srcImage.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, width, height, null);
           //获取绘图工具
            Graphics2D g1=buffImg.createGraphics();
            g1.drawImage(srcImage.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, width, height,null);
            
            g1.setColor(Color.BLACK); 
            g1.setFont(new Font("微软雅黑",Font.BOLD,50)); 
            g1.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.3F));
            int width1=50*getTextLength("某某某某学院");
            int height1=50;
            //旋转弧度
            g1.rotate(Math.toRadians(30), buffImg.getWidth()/2, buffImg.getHeight()/2);
            int x=-width/2;
            int y=-height/2;
            while(x<width*1.5){
                y=-height/2;
                while(y<height*1.5){
                    g1.drawString("某某某某学院",x,y); 
                    y+=height1+100;
                }
                x+=width1+100;
            }
            g1.dispose(); 
            return buffImg;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

因其中涉及到字体的长度在页面中的书写 以及英文与汉字长度的不一致 所以需要处理一下字体的大小

   public static  int getTextLength(String text){
       int length=text.length();
       for(int i=0;i<text.length();i++){
           String s=String.valueOf(text.charAt(i));
           if(s.getBytes().length>1){
               length++;
           }
       }
       length =length%2==0?length/2:length/2-1;
       return length;
   }

本案例的难点在处理 字符的位置以及旋转后,画布的长与款的大小设置以及字符的循环写入画布长度的判定

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: