java 图像处理

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

http://blog.csdn.net/zhangzhikaixinya/article/details/8459400

原文地址:https://www.cnblogs.com/MDK-L/p/4502175.html