图片网页水印系列

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 }

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="width: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

时间: 2024-08-18 03:11:51

图片网页水印系列的相关文章

图片加水印 图片验证码

图片加水印 1   获取这张图片 System.Drawing.Image img = System.Drawing.Image.FromStream(FileUpload1.FileContent); 2 给图片加水印 Graphics g = Graphics.FromImage(img); string s = "WWW.ITNBA.COM";         s 给图片加的水印文字 Font f = new Font("微软雅黑", 30); Brush b

网页设计系列之设计的基本原则

欢迎收看大奥编写的网页设计系列之设计的基本原则 本学习笔记根据<网页设计创意数卷2>修改而来,用它学习网页设计,将会带来全新的体验哦: 从多个设计中吸收灵感 设计的基本原则 重点 对比 平衡 对齐 重复 流 详细介绍 从多个设计中吸收灵感当你看到某个非常令人欣赏的网站时,你可能会产生自己也要做成那样的想法,而事实上这还不够,你要让自己继续在网上搜罗类似的网站,它们具有大致相同的结构.配色和内容,但是细节上各有各自的完美之处,我们要做的就是把各个网站的完美之处吸收进来,应用到自己的网站设计当中,

ASP.NET为图片加上水印

为我们发布的图片加上一个水印,也是我们经常要做的事情,那怎么样来做呢,下面就一步步开始吧 首先是一个制作水印的类:ImageHandler,代码如下: C#代码 using System; using System.IO; using System.Drawing; using System.Drawing.Imaging; using System.Data; using System.Configuration; using System.Linq; using System.Web; us

thinkphp 3.2.3整合ueditor 1.4,给上传的图片加水印

今天分享一下thinkphp 3.2.3整合ueditor 1.4,给上传的图片加水印.博主是新手,在这里卡住了很久(>_<) thinkphp 3.2.3整合ueditor 1.4 下载地址:https://github.com/Nintendov/Ueditor-thinkphp 下载下来,看着配置就可以了. 下面就是给上传图片加水印: (在做这步前,请确保ueditor已经正常工作) 我的工程目录如下: fonts里面的fz.fft为水印字体 images里面的logo.png为水印图片

java 图片加水印,设置透明度。说明很详细

package com.yidao.common; import java.awt.AlphaComposite; import java.awt.Graphics2D; import java.awt.Image; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.Out

文件上传,图片加水印

文件上传: 所用控件:FileUpload 使用时的思路: 1.判断用户是否选中了文件 FileUpload.FileName获取选中的文件名,判断长度,如果长度大于零就代表已经选择了文件 JS端:通过ID获取控件,然后控件的value获取选中的文件名 2.将文件保存到服务器上 FileUpload.SaveAs("绝对路径"); 3.获得绝对路径 先编写相对路径:比如"UpLoads/abc.txt" 再把路径映射成绝对路径:Server.MapPath(&quo

利用PHP为图片加水印

1.为图片加风格字体 <?php header('Content-type:image/jpeg');//告诉服务器用JPEG图像格式输出 $img=imagecreatefromjpeg('images/girl.jpg');//建立背景图像 $color=imagecolorallocate($img,100,100,100);//分配给字体的颜色 $width=imagesx($img);//输出背景图像的总宽度 $height=imagesy($img);//输出背景图像的总长度 $po

iOS图片加水印效果的实现并保存至相冊

图片加水印效果的实现并保存至相冊 实现效果如图: project下载:githubproject下载链接 代码: - (void)viewDidLoad { [super viewDidLoad]; UIImage *image = [UIImage imageNamed:@"pushu.jpg"]; UIImage *waterImage = [self waterMarkImage:image withText:@"朴树水印測试"]; UIImageWriteT

JAVA给图片加上水印

import java.awt.Color;       import java.awt.Font;       import java.awt.Graphics;       import java.awt.Image;       import java.awt.image.BufferedImage;       import java.io.File;       import java.io.FileOutputStream;       import com.sun.image.co