ImageUtils.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. package cn.com.ctop.common.utils;
  2. import java.awt.Color;
  3. import java.awt.Graphics2D;
  4. import java.awt.Image;
  5. import java.awt.Rectangle;
  6. import java.awt.image.BufferedImage;
  7. import java.io.File;
  8. import java.io.FileInputStream;
  9. import java.io.FileOutputStream;
  10. import java.io.IOException;
  11. import java.net.URL;
  12. import java.util.Date;
  13. import java.util.Iterator;
  14. import javax.imageio.ImageIO;
  15. import javax.imageio.ImageReadParam;
  16. import javax.imageio.ImageReader;
  17. import javax.imageio.stream.ImageInputStream;
  18. import com.sun.image.codec.jpeg.ImageFormatException;
  19. import com.sun.image.codec.jpeg.JPEGCodec;
  20. import com.sun.image.codec.jpeg.JPEGEncodeParam;
  21. import com.sun.image.codec.jpeg.JPEGImageEncoder;
  22. /**
  23. * 图片压缩工具类 提供的方法中可以设定生成的 缩略图片的大小尺寸、压缩尺寸的比例、图片的质量等
  24. * <pre>
  25. * 调用示例:
  26. * resiz(srcImg, tarDir + "car_1_maxLength_11-220px-hui.jpg", 220, 0.7F);
  27. * </pre>
  28. *
  29. * @author cevencheng
  30. * @project haohui-b2b
  31. * @create 2012-3-22 下午8:29:01
  32. */
  33. public class ImageUtils {
  34. /**
  35. * * 图片文件读取
  36. *
  37. * @param srcImgPath
  38. * @return
  39. */
  40. private static BufferedImage InputImage(String srcImgPath) throws RuntimeException {
  41. BufferedImage srcImage = null;
  42. FileInputStream in = null;
  43. try {
  44. // 构造BufferedImage对象
  45. File file = new File(srcImgPath);
  46. in = new FileInputStream(file);
  47. byte[] b = new byte[5];
  48. in.read(b);
  49. srcImage = javax.imageio.ImageIO.read(file);
  50. } catch (IOException e) {
  51. e.printStackTrace();
  52. throw new RuntimeException("读取图片文件出错!", e);
  53. } finally {
  54. if (in != null) {
  55. try {
  56. in.close();
  57. } catch (IOException e) {
  58. throw new RuntimeException("读取图片文件出错!", e);
  59. }
  60. }
  61. }
  62. return srcImage;
  63. }
  64. /**
  65. * * 将图片按照指定的图片尺寸、源图片质量压缩(默认质量为1)
  66. *
  67. * @param srcImgPath :源图片路径
  68. * @param outImgPath :输出的压缩图片的路径
  69. * @param new_w :压缩后的图片宽
  70. * @param new_h :压缩后的图片高
  71. */
  72. public static void resize(String srcImgPath, String outImgPath,
  73. int new_w, int new_h) {
  74. resize(srcImgPath, outImgPath, new_w, new_h, 1F);
  75. }
  76. /**
  77. * 将图片按照指定的尺寸比例、源图片质量压缩(默认质量为1)
  78. *
  79. * @param srcImgPath :源图片路径
  80. * @param outImgPath :输出的压缩图片的路径
  81. * @param ratio :压缩后的图片尺寸比例
  82. * :百分比
  83. */
  84. public static void resize(String srcImgPath, String outImgPath,
  85. float ratio) {
  86. resize(srcImgPath, outImgPath, ratio, 1F);
  87. }
  88. /**
  89. * 将图片按照指定长或者宽的最大值来压缩图片(默认质量为1)
  90. *
  91. * @param srcImgPath :源图片路径
  92. * @param outImgPath :输出的压缩图片的路径
  93. * @param maxLength :长或者宽的最大值
  94. * :图片质量
  95. */
  96. public static void resize(String srcImgPath, String outImgPath,
  97. int maxLength) {
  98. resize(srcImgPath, outImgPath, maxLength, 1F);
  99. }
  100. /**
  101. * * 将图片按照指定的图片尺寸、图片质量压缩
  102. *
  103. * @param srcImgPath :源图片路径
  104. * @param outImgPath :输出的压缩图片的路径
  105. * @param new_w :压缩后的图片宽
  106. * @param new_h :压缩后的图片高
  107. * @param per :百分比
  108. * @author cevencheng
  109. */
  110. public static void resize(String srcImgPath, String outImgPath,
  111. int new_w, int new_h, float per) {
  112. // 得到图片
  113. BufferedImage src = InputImage(srcImgPath);
  114. int old_w = src.getWidth();
  115. // 得到源图宽
  116. int old_h = src.getHeight();
  117. // 得到源图长
  118. // 根据原图的大小生成空白画布
  119. BufferedImage tempImg = new BufferedImage(old_w, old_h,
  120. BufferedImage.TYPE_INT_RGB);
  121. // 在新的画布上生成原图的缩略图
  122. Graphics2D g = tempImg.createGraphics();
  123. g.setColor(Color.white);
  124. g.fillRect(0, 0, old_w, old_h);
  125. g.drawImage(src, 0, 0, old_w, old_h, Color.white, null);
  126. g.dispose();
  127. BufferedImage newImg = new BufferedImage(new_w, new_h,
  128. BufferedImage.TYPE_INT_RGB);
  129. newImg.getGraphics().drawImage(
  130. tempImg.getScaledInstance(new_w, new_h, Image.SCALE_SMOOTH), 0,
  131. 0, null);
  132. // 调用方法输出图片文件
  133. outImage(outImgPath, newImg, per);
  134. }
  135. public static BufferedImage resize(BufferedImage src,
  136. int new_w, int new_h) {
  137. int old_w = src.getWidth();
  138. // 得到源图宽
  139. int old_h = src.getHeight();
  140. // 得到源图长
  141. // 根据原图的大小生成空白画布
  142. BufferedImage tempImg = new BufferedImage(old_w, old_h,
  143. BufferedImage.TYPE_INT_RGB);
  144. // 在新的画布上生成原图的缩略图
  145. Graphics2D g = tempImg.createGraphics();
  146. g.setColor(Color.white);
  147. g.fillRect(0, 0, old_w, old_h);
  148. g.drawImage(src, 0, 0, old_w, old_h, Color.white, null);
  149. g.dispose();
  150. BufferedImage newImg = new BufferedImage(new_w, new_h,
  151. BufferedImage.TYPE_INT_RGB);
  152. newImg.getGraphics().drawImage(
  153. tempImg, 0,
  154. 0, null);
  155. // 调用方法输出图片文件
  156. return newImg;
  157. }
  158. /**
  159. * * 将图片按照指定的尺寸比例、图片质量压缩
  160. *
  161. * @param srcImgPath :源图片路径
  162. * @param outImgPath :输出的压缩图片的路径
  163. * @param ratio :压缩后的图片尺寸比例
  164. * @param per :百分比
  165. * @author cevencheng
  166. */
  167. public static void resize(String srcImgPath, String outImgPath,
  168. float ratio, float per) {
  169. // 得到图片
  170. BufferedImage src = InputImage(srcImgPath);
  171. int old_w = src.getWidth();
  172. // 得到源图宽
  173. int old_h = src.getHeight();
  174. // 得到源图长
  175. int new_w = 0;
  176. // 新图的宽
  177. int new_h = 0;
  178. // 新图的长
  179. BufferedImage tempImg = new BufferedImage(old_w, old_h,
  180. BufferedImage.TYPE_INT_RGB);
  181. Graphics2D g = tempImg.createGraphics();
  182. g.setColor(Color.white);
  183. // 从原图上取颜色绘制新图g.fillRect(0, 0, old_w, old_h);
  184. g.drawImage(src, 0, 0, old_w, old_h, Color.white, null);
  185. g.dispose();
  186. // 根据图片尺寸压缩比得到新图的尺寸new_w = (int) Math.round(old_w * ratio);
  187. new_h = (int) Math.round(old_h * ratio);
  188. BufferedImage newImg = new BufferedImage(new_w, new_h,
  189. BufferedImage.TYPE_INT_RGB);
  190. newImg.getGraphics().drawImage(
  191. tempImg.getScaledInstance(new_w, new_h, Image.SCALE_SMOOTH), 0,
  192. 0, null);
  193. // 调用方法输出图片文件OutImage(outImgPath, newImg, per);
  194. }
  195. /**
  196. * <b>
  197. * 指定长或者宽的最大值来压缩图片
  198. * 推荐使用此方法
  199. * </b>
  200. *
  201. * @param srcImgPath :源图片路径
  202. * @param outImgPath :输出的压缩图片的路径
  203. * @param maxLength :长或者宽的最大值
  204. * @param per :图片质量
  205. * @author cevencheng
  206. */
  207. public static void resize(String srcImgPath, String outImgPath,
  208. int maxLength, float per) {
  209. // 得到图片
  210. BufferedImage src = InputImage(srcImgPath);
  211. int old_w = src.getWidth();
  212. // 得到源图宽
  213. int old_h = src.getHeight();
  214. // 得到源图长
  215. int new_w = 0;
  216. // 新图的宽
  217. int new_h = 0;
  218. // 新图的长
  219. BufferedImage tempImg = new BufferedImage(old_w, old_h,
  220. BufferedImage.TYPE_INT_RGB);
  221. Graphics2D g = tempImg.createGraphics();
  222. g.setColor(Color.white);
  223. // 从原图上取颜色绘制新图
  224. g.fillRect(0, 0, old_w, old_h);
  225. g.drawImage(src, 0, 0, old_w, old_h, Color.white, null);
  226. g.dispose();
  227. // 根据图片尺寸压缩比得到新图的尺寸
  228. if (old_w > old_h) {
  229. // 图片要缩放的比例
  230. new_w = maxLength;
  231. new_h = (int) Math.round(old_h * ((float) maxLength / old_w));
  232. } else {
  233. new_w = (int) Math.round(old_w * ((float) maxLength / old_h));
  234. new_h = maxLength;
  235. }
  236. BufferedImage newImg = new BufferedImage(new_w, new_h,
  237. BufferedImage.TYPE_INT_RGB);
  238. newImg.getGraphics().drawImage(
  239. tempImg.getScaledInstance(new_w, new_h, Image.SCALE_SMOOTH), 0,
  240. 0, null);
  241. // 调用方法输出图片文件
  242. outImage(outImgPath, newImg, per);
  243. }
  244. /**
  245. * 将图片压缩成指定宽度, 高度等比例缩放
  246. *
  247. * @param srcImgPath
  248. * @param outImgPath
  249. * @param width
  250. * @param per
  251. */
  252. public static void resizeFixedWidth(String srcImgPath, String outImgPath,
  253. int width, float per) {
  254. // 得到图片
  255. BufferedImage src = InputImage(srcImgPath);
  256. int old_w = src.getWidth();
  257. // 得到源图宽
  258. int old_h = src.getHeight();
  259. // 得到源图长
  260. int new_w = 0;
  261. // 新图的宽
  262. int new_h = 0;
  263. // 新图的长
  264. BufferedImage tempImg = new BufferedImage(old_w, old_h,
  265. BufferedImage.TYPE_INT_RGB);
  266. Graphics2D g = tempImg.createGraphics();
  267. g.setColor(Color.white);
  268. // 从原图上取颜色绘制新图
  269. g.fillRect(0, 0, old_w, old_h);
  270. g.drawImage(src, 0, 0, old_w, old_h, Color.white, null);
  271. g.dispose();
  272. // 根据图片尺寸压缩比得到新图的尺寸
  273. if (old_w > old_h) {
  274. // 图片要缩放的比例
  275. new_w = width;
  276. new_h = (int) Math.round(old_h * ((float) width / old_w));
  277. } else {
  278. new_w = (int) Math.round(old_w * ((float) width / old_h));
  279. new_h = width;
  280. }
  281. BufferedImage newImg = new BufferedImage(new_w, new_h,
  282. BufferedImage.TYPE_INT_RGB);
  283. newImg.getGraphics().drawImage(
  284. tempImg.getScaledInstance(new_w, new_h, Image.SCALE_SMOOTH), 0,
  285. 0, null);
  286. // 调用方法输出图片文件
  287. outImage(outImgPath, newImg, per);
  288. }
  289. /**
  290. * * 将图片文件输出到指定的路径,并可设定压缩质量
  291. *
  292. * @param outImgPath
  293. * @param newImg
  294. * @param per
  295. * @author cevencheng
  296. */
  297. private static void outImage(String outImgPath, BufferedImage newImg, float per) {
  298. // 判断输出的文件夹路径是否存在,不存在则创建
  299. File file = new File(outImgPath);
  300. if (!file.getParentFile().exists()) {
  301. file.getParentFile().mkdirs();
  302. }
  303. // 输出到文件流
  304. FileOutputStream fos = null;
  305. try {
  306. fos = new FileOutputStream(outImgPath);
  307. JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);
  308. JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(newImg);
  309. // 压缩质量
  310. jep.setQuality(per, true);
  311. encoder.encode(newImg, jep);
  312. fos.close();
  313. } catch (Exception e) {
  314. throw new RuntimeException(e);
  315. } finally {
  316. if (fos != null) {
  317. try {
  318. fos.close();
  319. } catch (IOException e) {
  320. throw new RuntimeException(e);
  321. }
  322. }
  323. }
  324. }
  325. /**
  326. * 图片剪切工具方法
  327. *
  328. * @param srcfile 源图片
  329. * @param outfile 剪切之后的图片
  330. * @param x 剪切顶点 X 坐标
  331. * @param y 剪切顶点 Y 坐标
  332. * @param width 剪切区域宽度
  333. * @param height 剪切区域高度
  334. * @throws IOException
  335. * @author cevencheng
  336. */
  337. public static void cut(File srcfile, File outfile, int x, int y, int width, int height) throws IOException {
  338. FileInputStream is = null;
  339. ImageInputStream iis = null;
  340. try {
  341. // 读取图片文件
  342. is = new FileInputStream(srcfile);
  343. /*
  344. * 返回包含所有当前已注册 ImageReader 的 Iterator,这些 ImageReader 声称能够解码指定格式。
  345. * 参数:formatName - 包含非正式格式名称 .(例如 "jpeg" 或 "tiff")等 。
  346. */
  347. Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName("jpg");
  348. ImageReader reader = it.next();
  349. // 获取图片流
  350. iis = ImageIO.createImageInputStream(is);
  351. /*
  352. * <p>iis:读取源.true:只向前搜索 </p>.将它标记为 ‘只向前搜索’。
  353. * 此设置意味着包含在输入源中的图像将只按顺序读取,可能允许 reader 避免缓存包含与以前已经读取的图像关联的数据的那些输入部分。
  354. */
  355. reader.setInput(iis, true);
  356. /*
  357. * <p>描述如何对流进行解码的类<p>.用于指定如何在输入时从 Java Image I/O
  358. * 框架的上下文中的流转换一幅图像或一组图像。用于特定图像格式的插件 将从其 ImageReader 实现的
  359. * getDefaultReadParam 方法中返回 ImageReadParam 的实例。
  360. */
  361. ImageReadParam param = reader.getDefaultReadParam();
  362. /*
  363. * 图片裁剪区域。Rectangle 指定了坐标空间中的一个区域,通过 Rectangle 对象
  364. * 的左上顶点的坐标(x,y)、宽度和高度可以定义这个区域。
  365. */
  366. Rectangle rect = new Rectangle(x, y, width, height);
  367. // 提供一个 BufferedImage,将其用作解码像素数据的目标。
  368. param.setSourceRegion(rect);
  369. /*
  370. * 使用所提供的 ImageReadParam 读取通过索引 imageIndex 指定的对象,并将 它作为一个完整的
  371. * BufferedImage 返回。
  372. */
  373. BufferedImage bi = reader.read(0, param);
  374. // 保存新图片
  375. ImageIO.write(bi, "jpg", outfile);
  376. } finally {
  377. if (is != null) {
  378. is.close();
  379. }
  380. if (iis != null) {
  381. iis.close();
  382. }
  383. }
  384. }
  385. public static void main(String args[]) throws Exception {
  386. String srcImg = "D:/sm.png";
  387. String tarDir = "d:/";
  388. // URL url = ImageUtils.class.getResource("src-2012.jpg");
  389. File srcfile = new File(srcImg);
  390. // System.out.println(url);
  391. System.out.println(srcfile.exists() + ", dir=" + srcfile.getParent());
  392. tarDir = srcfile.getParent();
  393. srcImg = srcfile.getPath();
  394. System.out.println("srcImg=" + srcImg);
  395. long startTime = new Date().getTime();
  396. resize(srcImg, tarDir + "car_1_maxLength_1-200px.jpg", 200);
  397. // Tosmallerpic(srcImg, tarDir + "car_1_maxLength_2.jpg", 0.5F);
  398. resize(srcImg, tarDir + "car_1_maxLength_3.jpg", 280, 112);
  399. resize(srcImg, tarDir + "car_1_maxLength_4-400x400.jpg", 220, 220);
  400. resize(srcImg, tarDir + "car_1_maxLength_11-220px-yinhui.jpg", 220, 0.7F);
  401. // Tosmallerpic(srcImg, tarDir + "car_1_maxLength_22.jpg", 0.5F, 0.8F);
  402. resize(srcImg, tarDir + "car_1_maxLength_33.jpg", 400, 500, 0.8F);
  403. System.out.println(new Date().getTime() - startTime);
  404. }
  405. }