直接上代码:

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

java图片处理工具类的更多相关文章

  1. java 图片处理工具类

    import java.awt.Image;  import java.awt.Rectangle;  import java.awt.geom.AffineTransform;  import ja ...

  2. 图片处理工具类 - ImageUtils.java

    纯JAVA实现的图片处理工具类,提供图片的裁剪.压缩.获取尺寸.制作圆角等方法. 源码如下:(点击下载 -ImageUtils.java .FolderUtils.java .commons-io-2 ...

  3. Java操作图片的工具类

    操作图片的工具类: import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Font; import java.a ...

  4. Java的图片处理工具类

    import Java.awt.AlphaComposite; import java.awt.Color; import java.awt.Font; import java.awt.Graphic ...

  5. 【转】java缩放图片、java裁剪图片代码工具类

    一首先看下效果 二工具类 三测试类 在系统的上传图片功能中,我们无法控制用户上传图片的大小,用户可能会上传大到几十M小到1k的的图片,一方面图片太大占据了太多的空间,另一方面,我们没办法在页面上显示统 ...

  6. Java常用工具类---image图片处理工具类、Json工具类

    package com.jarvis.base.util; import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStre ...

  7. 图片水印工具类java

    关于jar包的导入我就不多说了,我会把引入的jar包显示出来,大家自行Google package com.net.util; import java.awt.AlphaComposite; impo ...

  8. java文件处理工具类

    import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedRead ...

  9. Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类

    Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类 ============================== ©Copyright 蕃薯耀 20 ...

随机推荐

  1. CSS样式的优势

    为什么使用css样式来设置网页的外观样式呢?下面是一段文字,我们想把“超酷的互联网”.“服务及时贴心”.“有趣易学”这三个短语的文本颜色设置为红色,这时就 可以通过设置样式来设置,而且只需要编写一条c ...

  2. PHP Predefined Interfaces 预定义接口

    SPL提供了6个迭代器接口: Traversable 遍历接口(检测一个类是否可以使用 foreach 进行遍历的接口) Iterator 迭代器接口(可在内部迭代自己的外部迭代器或类的接口) Ite ...

  3. Navicat 选择语句

    1.进入数据库后,点击Query 2.点击new query 3.左边提供界面的筛选条件,如果不清楚sql语句,可直接在上面操作 4.右边可自己编写sql语句 5.写完语句后,点击Run,在resul ...

  4. OpenGL画图旋转

    #include<gl/glut.h>#include<gl/GL.h>#include<gl/GLU.h>#include<math.h>#inclu ...

  5. Groovy创建和解析json

    正文:  在Groovy 1.8发布新闻中,提到Groovy增加了对JSON的支持.Dustin Marx在其博文中,讲述了这一功能的使用. 用法真的很简单,创建一个JSON对象: import gr ...

  6. TP开发小技巧

    TP开发小技巧原文地址http://wp.chenyuanzhao.com/wp/2016/07/23/tp%E5%BC%80%E5%8F%91%E5%B0%8F%E6%8A%80%E5%B7%A7/ ...

  7. Js监控回车事件

    标题通俗的说,也就是绑定当用户按下回车键要执行的事件. 下面,入正题. 第一步,先编写简单的页面代码,这里我们只需要一个按钮就足够了.当然,还有按钮事件. <html> <head& ...

  8. C语言 位操作

    c语言位操作中需要注意有: 位操作只针对整型和字符型数据 在右移操作中:对无符号数和有符号中的正数补 0:符号数中的负数,取决于所使用的系统:补 0 的称为“逻辑右移”,补 1 的称为“算术右移”. ...

  9. GIve Me A Welcome Hug!

    类似于初来乍到,和大家打个招呼,并矫情的希望路人也能回赠我一个welcome hug. 到了这种园子那一定是做CS相关的了,一直以为如果能够坚持写技术博客,那一定会对自己的内力有十足的提升.借用一位前 ...

  10. express+jade+bootstrap+mongdb simple CRUD test

    1:当前环境 y@y:~$ node --version && express -V && mongo --version v0.12.2 MongoDB shell ...