• 图片网页水印系列


    1、java图片处理 (文字水印、图片水印、缩放、补白)

      1 package com.hmw.picMark;
      2 
      3 import java.awt.AlphaComposite;
      4 import java.awt.Color;
      5 import java.awt.Font;
      6 import java.awt.Graphics2D;
      7 import java.awt.Image;
      8 import java.awt.geom.AffineTransform;
      9 import java.awt.image.AffineTransformOp;
     10 import java.awt.image.BufferedImage;
     11 import java.io.File;
     12 import java.io.IOException;
     13 
     14 import javax.imageio.ImageIO;
     15 
     16 /**
     17  * 图片工具类, 图片水印,文字水印,缩放,补白等
     18  * @author Carl He
     19  */
     20 public final class ImageUtils {
     21     /**图片格式:JPG*/
     22     private static final String PICTRUE_FORMATE_JPG = "jpg";
     23     
     24     private ImageUtils(){}
     25     /**
     26      * 添加图片水印
     27      * @param targetImg 目标图片路径,如:C://myPictrue//1.jpg
     28      * @param waterImg  水印图片路径,如:C://myPictrue//logo.png
     29      * @param x 水印图片距离目标图片左侧的偏移量,如果x<0, 则在正中间
     30      * @param y 水印图片距离目标图片上侧的偏移量,如果y<0, 则在正中间
     31      * @param alpha 透明度(0.0 -- 1.0, 0.0为完全透明,1.0为完全不透明)
     32 */
     33     public final static void pressImage(String targetImg, String waterImg, int x, int y, float alpha) {
     34             try {
     35                 File file = new File(targetImg);
     36                 Image image = ImageIO.read(file);
     37                 int width = image.getWidth(null);
     38                 int height = image.getHeight(null);
     39                 BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
     40                 Graphics2D g = bufferedImage.createGraphics();
     41                 g.drawImage(image, 0, 0, width, height, null);
     42             
     43                 Image waterImage = ImageIO.read(new File(waterImg));    // 水印文件
     44                 int width_1 = waterImage.getWidth(null);
     45                 int height_1 = waterImage.getHeight(null);
     46                 g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
     47                 
     48                 int widthDiff = width - width_1;
     49                 int heightDiff = height - height_1;
     50                 if(x < 0){
     51                     x = widthDiff / 2;
     52                 }else if(x > widthDiff){
     53                     x = widthDiff;
     54                 }
     55                 if(y < 0){
     56                     y = heightDiff / 2;
     57                 }else if(y > heightDiff){
     58                     y = heightDiff;
     59                 }
     60                 g.drawImage(waterImage, x, y, width_1, height_1, null); // 水印文件结束
     61                 g.dispose();
     62                 ImageIO.write(bufferedImage, PICTRUE_FORMATE_JPG, file);
     63             } catch (IOException e) {
     64                 e.printStackTrace();
     65             }
     66     }
     67 
     68     /**
     69      * 添加文字水印
     70      * @param targetImg 目标图片路径,如:C://myPictrue//1.jpg
     71      * @param pressText 水印文字, 如:中国证券网
     72      * @param fontName 字体名称,    如:宋体
     73      * @param fontStyle 字体样式,如:粗体和斜体(Font.BOLD|Font.ITALIC)
     74      * @param fontSize 字体大小,单位为像素
     75      * @param color 字体颜色
     76      * @param x 水印文字距离目标图片左侧的偏移量,如果x<0, 则在正中间
     77      * @param y 水印文字距离目标图片上侧的偏移量,如果y<0, 则在正中间
     78      * @param alpha 透明度(0.0 -- 1.0, 0.0为完全透明,1.0为完全不透明)
     79 */
     80     public static void pressText(String targetImg, String pressText, String fontName, int fontStyle, int fontSize, Color color, int x, int y, float alpha) {
     81         try {
     82             File file = new File(targetImg);
     83             
     84             Image image = ImageIO.read(file);
     85             int width = image.getWidth(null);
     86             int height = image.getHeight(null);
     87             BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
     88             Graphics2D g = bufferedImage.createGraphics();
     89             g.drawImage(image, 0, 0, width, height, null);
     90             g.setFont(new Font(fontName, fontStyle, fontSize));
     91             g.setColor(color);
     92             g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
     93             
     94             int width_1 = fontSize * getLength(pressText);
     95             int height_1 = fontSize;
     96             int widthDiff = width - width_1;
     97             int heightDiff = height - height_1;
     98             if(x < 0){
     99                 x = widthDiff / 2;
    100             }else if(x > widthDiff){
    101                 x = widthDiff;
    102             }
    103             if(y < 0){
    104                 y = heightDiff / 2;
    105             }else if(y > heightDiff){
    106                 y = heightDiff;
    107             }
    108             
    109             g.drawString(pressText, x, y + height_1);
    110             g.dispose();
    111             ImageIO.write(bufferedImage, PICTRUE_FORMATE_JPG, file);
    112         } catch (Exception e) {
    113             e.printStackTrace();
    114         }
    115     }
    116     
    117     /**
    118      * 获取字符长度,一个汉字作为 1 个字符, 一个英文字母作为 0.5 个字符
    119      * @param text
    120      * @return 字符长度,如:text="中国",返回 2;text="test",返回 2;text="中国ABC",返回 4.
    121 */
    122     public static int getLength(String text) {
    123         int textLength = text.length();
    124         int length = textLength;
    125         for (int i = 0; i < textLength; i++) {
    126             if (String.valueOf(text.charAt(i)).getBytes().length > 1) {
    127                 length++;
    128             }
    129         }
    130         return (length % 2 == 0) ? length / 2 : length / 2 + 1;
    131     }
    132 
    133     /**
    134      * 图片缩放
    135      * @param filePath 图片路径
    136      * @param height 高度
    137      * @param width 宽度
    138      * @param bb 比例不对时是否需要补白
    139 */
    140     public static void resize(String filePath, int height, int width, boolean bb) {
    141         try {
    142             double ratio = 0; //缩放比例    
    143             File f = new File(filePath);   
    144             BufferedImage bi = ImageIO.read(f);   
    145             Image itemp = bi.getScaledInstance(width, height, BufferedImage.SCALE_SMOOTH);   
    146             //计算比例   
    147             if ((bi.getHeight() > height) || (bi.getWidth() > width)) {   
    148                 if (bi.getHeight() > bi.getWidth()) {   
    149                     ratio = (new Integer(height)).doubleValue() / bi.getHeight();   
    150                 } else {   
    151                     ratio = (new Integer(width)).doubleValue() / bi.getWidth();   
    152                 }   
    153                 AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);   
    154                 itemp = op.filter(bi, null);   
    155             }   
    156             if (bb) {   
    157                 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);   
    158                 Graphics2D g = image.createGraphics();   
    159                 g.setColor(Color.white);   
    160                 g.fillRect(0, 0, width, height);   
    161                 if (width == itemp.getWidth(null))   
    162                     g.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2, itemp.getWidth(null), itemp.getHeight(null), Color.white, null);   
    163                 else  
    164                     g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0, itemp.getWidth(null), itemp.getHeight(null), Color.white, null);   
    165                 g.dispose();   
    166                 itemp = image;   
    167             }
    168             ImageIO.write((BufferedImage) itemp, "jpg", f);   
    169         } catch (IOException e) {
    170             e.printStackTrace();
    171         }
    172     }
    173 
    174     public static void main(String[] args) throws IOException {
    175         pressImage("C://pic//jpg", "C://pic//test.gif", 5000, 5000, 0f);
    176         pressText("C://pic//jpg", "旺仔之印", "宋体", Font.BOLD|Font.ITALIC, 20, Color.BLACK, 0, 0, 8f);
    177         resize("C://pic//4.jpg", 1000, 500, true);
    178     }
    179 }
    View Code

    getLength 这个方法用来得到文字的长度 全角一个字 半角算半个字 但是感觉这种方法不太好 不知道有没有更好地方法~


    2、使用js给页面显示的图片添加水印效果

    功能描述:使用Jquery 给页面的图片添加 版权信息水印。

                  这里的水印并不是真的把每一张图片上都添加了水印。而是在图片的上方添加了一个层,层中包含了水印图片效果就像是图片上加了水印。

    功能原理:1,使用jquery 遍历页面的所有img标签,取得其位置信息
                  2,在body里边追加一个div,div中放水印图片,根据1中取得的位置,来确定水印div的相对位置。

    代码:

     1 $(function(){
     2              
     3                 
     4                 $("img").each(function(){
     5                     // 特殊情况--过滤掉无关的图片
     6                     if($(this).attr("id") == "img1"){
     7                         return;
     8                     }
     9                     
    10                     
    11                     var top = $(this).offset().top+10;//这里数字根据需要调,一般配在数据库中
    12                     var left = $(this).offset().left+10;
    13                     var styleString="250px;height:50px;display:block;position:absolute;left:"+left+"px;top:"+top+"px;";
    14                     var imageUrl="images/shuiyin.jpg";
    15                     //追加水印div
    16                     $(document.body).append('<div id="shuiyinDiv" style='+styleString+'><img src='+imageUrl+'></div>');
    17                 });
    js图片水印

    3、JS加水印遮罩

     1 <%@ page language="java" pageEncoding="utf-8"%>
     2 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     3 <html>
     4     <head>
     5         <title>悬浮水印</title>
     6         <meta http-equiv="pragma" content="no-cache">
     7         <meta http-equiv="cache-control" content="no-cache">
     8         <meta http-equiv="expires" content="0">
     9         <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    10         <meta http-equiv="description" content="This is my page">
    11         <script type="text/javascript" src="watermark.js"></script>
    12     </head>
    13     <body onload="GetWaterMarked(window,'watermark.jpg','this')">
    14         <div><font size="7">
    15         This is a test.<br>
    16         This is a test.<br>
    17         This is a test.<br>
    18         This is a test.<br>
    19         This is a test.<br>
    20         This is a test.<br>
    21         This is a test.<br>
    22         This is a test.<br>
    23         This is a test.<br>
    24         This is a test.<br>
    25         This is a test.<br>
    26         This is a test.<br>
    27         This is a test.<br>
    28         This is a test.<br>
    29         This is a test.<br>
    30         This is a test.<br>
    31         This is a test.<br>
    32         This is a test.<br>
    33         This is a test.<br>
    34         This is a test.<br>
    35         This is a test.<br>
    36         This is a test.<br>
    37         </font></div>
    38     </body>
    39 </html>
    页面代码
     1 function GetWaterMarked(targetObj,jpgUrl,targetStr ) {
     2         var windowobj=targetObj;
     3         var waterMarkPicUrl=jpgUrl;
     4         var controlWindowStr=targetStr;
     5         if(windowobj.document.getElementById("waterMark") != null)
     6             return;
     7         var m = "waterMark";
     8         var newMark = windowobj.document.createElement("div");
     9         newMark.id = m;
    10         
    11         //定义div绝对位置
    12         newMark.style.position = "absolute";
    13         newMark.style.top = "0px";
    14         newMark.style.left = "0px";
    15         //设置div堆叠顺序,若为正数,则离用户更近,为负,数则表示离用户更远
    16         newMark.style.zIndex = "99999";
    17         //使用浏览器宽
    18         newMark.style.width = windowobj.document.body.clientWidth;
    19         //页面实际长度(不显示竖向滚动条)>浏览器长
    20         if( parseInt(windowobj.document.body.scrollHeight) > parseInt(windowobj.document.body.clientHeight) ){
    21             newMark.style.height = windowobj.document.body.scrollHeight;
    22         }else{
    23             newMark.style.height = windowobj.document.body.clientHeight;
    24         }
    25         //使用水印图片设为div背景
    26         newMark.style.backgroundImage = "url("+ waterMarkPicUrl +")";
    27         //透明样式
    28         newMark.style.filter = "alpha(opacity=20)";
    29         //加入div
    30         windowobj.document.body.appendChild(newMark);
    31 
    32         var markStr = "var sobj ="+controlWindowStr+".document.getElementById('waterMark');sobj.style.width ="+controlWindowStr+".document.body.clientWidth;sobj.style.height ="+controlWindowStr+".document.body.clientHeight;";
    33         if(windowobj.document.body.onresize != null){
    34             var oldResiae = windowobj.document.body.onresize.toString();
    35              var oldResiaeStr = oldResiae.substr(oldResiae.indexOf("{")+1);
    36              var oldResiaeStr= oldResiaeStr.substr(0,oldResiaeStr.lastIndexOf("}"));
    37              oldResiaeStr+=";"+markStr;
    38              windowobj.document.body.onresize = new Function(oldResiaeStr);
    39         }else{
    40             windowobj.document.body.onresize = new Function(markStr);
    41         }
    42  }
    javascript
  • 相关阅读:
    vue视图刷新失效
    vue移动端框架搭建
    猜单词--莫妮卡的新游戏
    快速上手python的坑
    江西育华学校初三下月考英语试卷 2020.3
    Title
    什么是vuex? 什么场景下适用vuex?
    左右模块滑动
    vue-router的几种实例方法以及参数传递
    完整的 vue-router 导航解析流程
  • 原文地址:https://www.cnblogs.com/douglas0126x/p/5000612.html
Copyright © 2020-2023  润新知