图片处理类(图片水印 图片缩放)

本图片处理类功能很是之强大能够实现几乎全部WEB开发中对图像的处理功能都集成了,包括有缩放图像、切割图像、图像类型转换、彩色转黑白、文字水印、图片水印等功能
 
 
  1 import java.awt.AlphaComposite;
  2 import java.awt.Color;
  3 import java.awt.Font;
  4 import java.awt.Graphics;
  5 import java.awt.Graphics2D;
  6 import java.awt.Image;
  7 import java.awt.Toolkit;
  8 import java.awt.color.ColorSpace;
  9 import java.awt.geom.AffineTransform;
 10 import java.awt.image.AffineTransformOp;
 11 import java.awt.image.BufferedImage;
 12 import java.awt.image.ColorConvertOp;
 13 import java.awt.image.CropImageFilter;
 14 import java.awt.image.FilteredImageSource;
 15 import java.awt.image.ImageFilter;
 16 import java.io.File;
 17 import java.io.IOException;  
 18  import javax.imageio.ImageIO; 
 19  /**
 20  * 图片处理工具类:<br>
 21  * 功能:缩放图像、切割图像、图像类型转换、彩色转黑白、文字水印、图片水印等
 22  * @author Administrator
 23  */
 24 public class ImageUtils { 
 25      /**
 26      * 几种常见的图片格式
 27      */
 28     public static String IMAGE_TYPE_GIF = "gif";// 图形交换格式
 29     public static String IMAGE_TYPE_JPG = "jpg";// 联合照片专家组
 30     public static String IMAGE_TYPE_JPEG = "jpeg";// 联合照片专家组
 31     public static String IMAGE_TYPE_BMP = "bmp";// 英文Bitmap(位图)的简写,它是Windows操做系统中的标准图像文件格式
 32     public static String IMAGE_TYPE_PNG = "png";// 可移植网络图形
 33     public static String IMAGE_TYPE_PSD = "psd";// Photoshop的专用格式Photoshop 
 34      /**
 35      * 程序入口:用于测试
 36      * @param args
 37      */
 38     public static void main(String[] args) {
 39         // 1-缩放图像:
 40         // 方法一:按比例缩放
 41         ImageUtils.scale("e:/abc.jpg", "e:/abc_scale.jpg", 2, true);//测试OK
 42         // 方法二:按高度和宽度缩放
 43         ImageUtils.scale2("e:/abc.jpg", "e:/abc_scale2.jpg", 500, 300, true);//测试OK 
 44          // 2-切割图像:
 45         // 方法一:按指定起点坐标和宽高切割
 46         ImageUtils.cut("e:/abc.jpg", "e:/abc_cut.jpg", 0, 0, 400, 400 );//测试OK
 47         // 方法二:指定切片的行数和列数
 48         ImageUtils.cut2("e:/abc.jpg", "e:/", 2, 2 );//测试OK
 49         // 方法三:指定切片的宽度和高度
 50         ImageUtils.cut3("e:/abc.jpg", "e:/", 300, 300 );//测试OK 
 51          // 3-图像类型转换:
 52         ImageUtils.convert("e:/abc.jpg", "GIF", "e:/abc_convert.gif");//测试OK 
 53          // 4-彩色转黑白:
 54         ImageUtils.gray("e:/abc.jpg", "e:/abc_gray.jpg");//测试OK 
 55          // 5-给图片添加文字水印:
 56         // 方法一:
 57         ImageUtils.pressText("我是水印文字","e:/abc.jpg","e:/abc_pressText.jpg","宋体",Font.BOLD,Color.white,80, 0, 0, 0.5f);//测试OK
 58         // 方法二:
 59         ImageUtils.pressText2("我也是水印文字", "e:/abc.jpg","e:/abc_pressText2.jpg", "黑体", 36, Color.white, 80, 0, 0, 0.5f);//测试OK
 60 
 61         // 6-给图片添加图片水印:
 62         ImageUtils.pressImage("e:/abc2.jpg", "e:/abc.jpg","e:/abc_pressImage.jpg", 0, 0, 0.5f);//测试OK
 63     } 
 64      /**
 65      * 缩放图像(按比例缩放)
 66      * @param srcImageFile 源图像文件地址
 67      * @param result 缩放后的图像地址
 68      * @param scale 缩放比例
 69      * @param flag 缩放选择:true 放大; false 缩小;
 70      */
 71     public final static void scale(String srcImageFile, String result,
 72             int scale, boolean flag) {
 73         try {
 74             BufferedImage src = ImageIO.read(new File(srcImageFile)); // 读入文件
 75             int width = src.getWidth(); // 获得源图宽
 76             int height = src.getHeight(); // 获得源图长
 77             if (flag) {// 放大
 78                 width = width * scale;
 79                 height = height * scale;
 80             } else {// 缩小
 81                 width = width / scale;
 82                 height = height / scale;
 83             }
 84             Image image = src.getScaledInstance(width, height,
 85                     Image.SCALE_DEFAULT);
 86             BufferedImage tag = new BufferedImage(width, height,
 87                     BufferedImage.TYPE_INT_RGB);
 88             Graphics g = tag.getGraphics();
 89             g.drawImage(image, 0, 0, null); // 绘制缩小后的图
 90             g.dispose();
 91             ImageIO.write(tag, "JPEG", new File(result));// 输出到文件流
 92         } catch (IOException e) {
 93             e.printStackTrace();
 94         }
 95     } 
 96      /**
 97      * 缩放图像(按高度和宽度缩放)
 98      * @param srcImageFile 源图像文件地址
 99      * @param result 缩放后的图像地址
100      * @param height 缩放后的高度
101      * @param width 缩放后的宽度
102      * @param bb 比例不对时是否须要补白:true为补白; false为不补白;
103      */
104     public final static void scale2(String srcImageFile, String result, int height, int width, boolean bb) {
105         try {
106             double ratio = 0.0; // 缩放比例
107             File f = new File(srcImageFile);
108             BufferedImage bi = ImageIO.read(f);
109             Image itemp = bi.getScaledInstance(width, height, bi.SCALE_SMOOTH);
110             // 计算比例
111             if ((bi.getHeight() > height) || (bi.getWidth() > width)) {
112                 if (bi.getHeight() > bi.getWidth()) {
113                     ratio = (new Integer(height)).doubleValue()
114                             / bi.getHeight();
115                 } else {
116                     ratio = (new Integer(width)).doubleValue() / bi.getWidth();
117                 }
118                 AffineTransformOp op = new AffineTransformOp(AffineTransform
119                         .getScaleInstance(ratio, ratio), null);
120                 itemp = op.filter(bi, null);
121             }
122             if (bb) {//补白
123                 BufferedImage image = new BufferedImage(width, height,
124                         BufferedImage.TYPE_INT_RGB);
125                 Graphics2D g = image.createGraphics();
126                 g.setColor(Color.white);
127                 g.fillRect(0, 0, width, height);
128                 if (width == itemp.getWidth(null))
129                     g.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2,
130                             itemp.getWidth(null), itemp.getHeight(null),
131                             Color.white, null);
132                 else
133                     g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0,
134                             itemp.getWidth(null), itemp.getHeight(null),
135                             Color.white, null);
136                 g.dispose();
137                 itemp = image;
138             }
139             ImageIO.write((BufferedImage) itemp, "JPEG", new File(result));
140         } catch (IOException e) {
141             e.printStackTrace();
142         }
143     }
144 
145     /**
146      * 图像切割(按指定起点坐标和宽高切割)
147      * @param srcImageFile 源图像地址
148      * @param result 切片后的图像地址
149      * @param x 目标切片起点坐标X
150      * @param y 目标切片起点坐标Y
151      * @param width 目标切片宽度
152      * @param height 目标切片高度
153      */
154     public final static void cut(String srcImageFile, String result,
155             int x, int y, int width, int height) {
156         try {
157             // 读取源图像
158             BufferedImage bi = ImageIO.read(new File(srcImageFile));
159             int srcWidth = bi.getHeight(); // 源图宽度
160             int srcHeight = bi.getWidth(); // 源图高度
161             if (srcWidth > 0 && srcHeight > 0) {
162                 Image image = bi.getScaledInstance(srcWidth, srcHeight,
163                         Image.SCALE_DEFAULT);
164                 // 四个参数分别为图像起点坐标和宽高
165                 // 即: CropImageFilter(int x,int y,int width,int height)
166                 ImageFilter cropFilter = new CropImageFilter(x, y, width, height);
167                 Image img = Toolkit.getDefaultToolkit().createImage(
168                         new FilteredImageSource(image.getSource(),
169                                 cropFilter));
170                 BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
171                 Graphics g = tag.getGraphics();
172                 g.drawImage(img, 0, 0, width, height, null); // 绘制切割后的图
173                 g.dispose();
174                 // 输出为文件
175                 ImageIO.write(tag, "JPEG", new File(result));
176             }
177         } catch (Exception e) {
178             e.printStackTrace();
179         }
180     }
181 
182     /**
183      * 图像切割(指定切片的行数和列数)
184      * @param srcImageFile 源图像地址
185      * @param descDir 切片目标文件夹
186      * @param rows 目标切片行数。默认2,必须是范围 [1, 20] 以内
187      * @param cols 目标切片列数。默认2,必须是范围 [1, 20] 以内
188      */
189     public final static void cut2(String srcImageFile, String descDir,
190             int rows, int cols) {
191         try {
192             if(rows<=0||rows>20) rows = 2; // 切片行数
193             if(cols<=0||cols>20) cols = 2; // 切片列数
194             // 读取源图像
195             BufferedImage bi = ImageIO.read(new File(srcImageFile));
196             int srcWidth = bi.getHeight(); // 源图宽度
197             int srcHeight = bi.getWidth(); // 源图高度
198             if (srcWidth > 0 && srcHeight > 0) {
199                 Image img;
200                 ImageFilter cropFilter;
201                 Image image = bi.getScaledInstance(srcWidth, srcHeight, Image.SCALE_DEFAULT);
202                 int destWidth = srcWidth; // 每张切片的宽度
203                 int destHeight = srcHeight; // 每张切片的高度
204                 // 计算切片的宽度和高度
205                 if (srcWidth % cols == 0) {
206                     destWidth = srcWidth / cols;
207                 } else {
208                     destWidth = (int) Math.floor(srcWidth / cols) + 1;
209                 }
210                 if (srcHeight % rows == 0) {
211                     destHeight = srcHeight / rows;
212                 } else {
213                     destHeight = (int) Math.floor(srcWidth / rows) + 1;
214                 }
215                 // 循环创建切片
216                 // 改进的想法:是否可用多线程加快切割速度
217                 for (int i = 0; i < rows; i++) {
218                     for (int j = 0; j < cols; j++) {
219                         // 四个参数分别为图像起点坐标和宽高
220                         // 即: CropImageFilter(int x,int y,int width,int height)
221                         cropFilter = new CropImageFilter(j * destWidth, i * destHeight,
222                                 destWidth, destHeight);
223                         img = Toolkit.getDefaultToolkit().createImage(
224                                 new FilteredImageSource(image.getSource(),
225                                         cropFilter));
226                         BufferedImage tag = new BufferedImage(destWidth,
227                                 destHeight, BufferedImage.TYPE_INT_RGB);
228                         Graphics g = tag.getGraphics();
229                         g.drawImage(img, 0, 0, null); // 绘制缩小后的图
230                         g.dispose();
231                         // 输出为文件
232                         ImageIO.write(tag, "JPEG", new File(descDir
233                                 + "_r" + i + "_c" + j + ".jpg"));
234                     }
235                 }
236             }
237         } catch (Exception e) {
238             e.printStackTrace();
239         }
240     } 
241      /**
242      * 图像切割(指定切片的宽度和高度)
243      * @param srcImageFile 源图像地址
244      * @param descDir 切片目标文件夹
245      * @param destWidth 目标切片宽度。默认200
246      * @param destHeight 目标切片高度。默认150
247      */
248     public final static void cut3(String srcImageFile, String descDir,
249             int destWidth, int destHeight) {
250         try {
251             if(destWidth<=0) destWidth = 200; // 切片宽度
252             if(destHeight<=0) destHeight = 150; // 切片高度
253             // 读取源图像
254             BufferedImage bi = ImageIO.read(new File(srcImageFile));
255             int srcWidth = bi.getHeight(); // 源图宽度
256             int srcHeight = bi.getWidth(); // 源图高度
257             if (srcWidth > destWidth && srcHeight > destHeight) {
258                 Image img;
259                 ImageFilter cropFilter;
260                 Image image = bi.getScaledInstance(srcWidth, srcHeight, Image.SCALE_DEFAULT);
261                 int cols = 0; // 切片横向数量
262                 int rows = 0; // 切片纵向数量
263                 // 计算切片的横向和纵向数量
264                 if (srcWidth % destWidth == 0) {
265                     cols = srcWidth / destWidth;
266                 } else {
267                     cols = (int) Math.floor(srcWidth / destWidth) + 1;
268                 }
269                 if (srcHeight % destHeight == 0) {
270                     rows = srcHeight / destHeight;
271                 } else {
272                     rows = (int) Math.floor(srcHeight / destHeight) + 1;
273                 }
274                 // 循环创建切片
275                 // 改进的想法:是否可用多线程加快切割速度
276                 for (int i = 0; i < rows; i++) {
277                     for (int j = 0; j < cols; j++) {
278                         // 四个参数分别为图像起点坐标和宽高
279                         // 即: CropImageFilter(int x,int y,int width,int height)
280                         cropFilter = new CropImageFilter(j * destWidth, i * destHeight,
281                                 destWidth, destHeight);
282                         img = Toolkit.getDefaultToolkit().createImage(
283                                 new FilteredImageSource(image.getSource(),
284                                         cropFilter));
285                         BufferedImage tag = new BufferedImage(destWidth,
286                                 destHeight, BufferedImage.TYPE_INT_RGB);
287                         Graphics g = tag.getGraphics();
288                         g.drawImage(img, 0, 0, null); // 绘制缩小后的图
289                         g.dispose();
290                         // 输出为文件
291                         ImageIO.write(tag, "JPEG", new File(descDir
292                                 + "_r" + i + "_c" + j + ".jpg"));
293                     }
294                 }
295             }
296         } catch (Exception e) {
297             e.printStackTrace();
298         }
299     } 
300      /**
301      * 图像类型转换:GIF->JPG、GIF->PNG、PNG->JPG、PNG->GIF(X)、BMP->PNG
302      * @param srcImageFile 源图像地址
303      * @param formatName 包含格式非正式名称的 String:如JPG、JPEG、GIF等
304      * @param destImageFile 目标图像地址
305      */
306     public final static void convert(String srcImageFile, String formatName, String destImageFile) {
307         try {
308             File f = new File(srcImageFile);
309             f.canRead();
310             f.canWrite();
311             BufferedImage src = ImageIO.read(f);
312             ImageIO.write(src, formatName, new File(destImageFile));
313         } catch (Exception e) {
314             e.printStackTrace();
315         }
316     } 
317      /**
318      * 彩色转为黑白 
319      * @param srcImageFile 源图像地址
320      * @param destImageFile 目标图像地址
321      */
322     public final static void gray(String srcImageFile, String destImageFile) {
323         try {
324             BufferedImage src = ImageIO.read(new File(srcImageFile));
325             ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
326             ColorConvertOp op = new ColorConvertOp(cs, null);
327             src = op.filter(src, null);
328             ImageIO.write(src, "JPEG", new File(destImageFile));
329         } catch (IOException e) {
330             e.printStackTrace();
331         }
332     } 
333      /**
334      * 给图片添加文字水印
335      * @param pressText 水印文字
336      * @param srcImageFile 源图像地址
337      * @param destImageFile 目标图像地址
338      * @param fontName 水印的字体名称
339      * @param fontStyle 水印的字体样式
340      * @param color 水印的字体颜色
341      * @param fontSize 水印的字体大小
342      * @param x 修正值
343      * @param y 修正值
344      * @param alpha 透明度:alpha 必须是范围 [0.0, 1.0] 以内(包含边界值)的一个浮点数字
345      */
346     public final static void pressText(String pressText,
347             String srcImageFile, String destImageFile, String fontName,
348             int fontStyle, Color color, int fontSize,int x,
349             int y, float alpha) {
350         try {
351             File img = new File(srcImageFile);
352             Image src = ImageIO.read(img);
353             int width = src.getWidth(null);
354             int height = src.getHeight(null);
355             BufferedImage image = new BufferedImage(width, height,
356                     BufferedImage.TYPE_INT_RGB);
357             Graphics2D g = image.createGraphics();
358             g.drawImage(src, 0, 0, width, height, null);
359             g.setColor(color);
360             g.setFont(new Font(fontName, fontStyle, fontSize));
361             g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
362                     alpha));
363             // 在指定坐标绘制水印文字
364             g.drawString(pressText, (width - (getLength(pressText) * fontSize))
365                     / 2 + x, (height - fontSize) / 2 + y);
366             g.dispose();
367             ImageIO.write((BufferedImage) image, "JPEG", new File(destImageFile));// 输出到文件流
368         } catch (Exception e) {
369             e.printStackTrace();
370         }
371     } 
372      /**
373      * 给图片添加文字水印
374      * @param pressText 水印文字
375      * @param srcImageFile 源图像地址
376      * @param destImageFile 目标图像地址
377      * @param fontName 字体名称
378      * @param fontStyle 字体样式
379      * @param color 字体颜色
380      * @param fontSize 字体大小
381      * @param x 修正值
382      * @param y 修正值
383      * @param alpha 透明度:alpha 必须是范围 [0.0, 1.0] 以内(包含边界值)的一个浮点数字
384      */
385     public final static void pressText2(String pressText, String srcImageFile,String destImageFile,
386             String fontName, int fontStyle, Color color, int fontSize, int x,
387             int y, float alpha) {
388         try {
389             File img = new File(srcImageFile);
390             Image src = ImageIO.read(img);
391             int width = src.getWidth(null);
392             int height = src.getHeight(null);
393             BufferedImage image = new BufferedImage(width, height,
394                     BufferedImage.TYPE_INT_RGB);
395             Graphics2D g = image.createGraphics();
396             g.drawImage(src, 0, 0, width, height, null);
397             g.setColor(color);
398             g.setFont(new Font(fontName, fontStyle, fontSize));
399             g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
400                     alpha));
401             // 在指定坐标绘制水印文字
402             g.drawString(pressText, (width - (getLength(pressText) * fontSize))
403                     / 2 + x, (height - fontSize) / 2 + y);
404             g.dispose();
405             ImageIO.write((BufferedImage) image, "JPEG", new File(destImageFile));
406         } catch (Exception e) {
407             e.printStackTrace();
408         }
409     } 
410      /**
411      * 给图片添加图片水印
412      * @param pressImg 水印图片
413      * @param srcImageFile 源图像地址
414      * @param destImageFile 目标图像地址
415      * @param x 修正值。 默认在中间
416      * @param y 修正值。 默认在中间
417      * @param alpha 透明度:alpha 必须是范围 [0.0, 1.0] 以内(包含边界值)的一个浮点数字
418      */
419     public final static void pressImage(String pressImg, String srcImageFile,String destImageFile,
420             int x, int y, float alpha) {
421         try {
422             File img = new File(srcImageFile);
423             Image src = ImageIO.read(img);
424             int wideth = src.getWidth(null);
425             int height = src.getHeight(null);
426             BufferedImage image = new BufferedImage(wideth, height,
427                     BufferedImage.TYPE_INT_RGB);
428             Graphics2D g = image.createGraphics();
429             g.drawImage(src, 0, 0, wideth, height, null);
430             // 水印文件
431             Image src_biao = ImageIO.read(new File(pressImg));
432             int wideth_biao = src_biao.getWidth(null);
433             int height_biao = src_biao.getHeight(null);
434             g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
435                     alpha));
436             g.drawImage(src_biao, (wideth - wideth_biao) / 2,
437                     (height - height_biao) / 2, wideth_biao, height_biao, null);
438             // 水印文件结束
439             g.dispose();
440             ImageIO.write((BufferedImage) image,  "JPEG", new File(destImageFile));
441         } catch (Exception e) {
442             e.printStackTrace();
443         }
444     } 
445      /**
446      * 计算text的长度(一个中文算两个字符)
447      * @param text
448      * @return
449      */
450     public final static int getLength(String text) {
451         int length = 0;
452         for (int i = 0; i < text.length(); i++) {
453             if (new String(text.charAt(i) + "").getBytes().length > 1) {
454                 length += 2;
455             } else {
456                 length += 1;
457             }
458         }
459         return length / 2;
460     }
461 }
462