在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

java实现图片压缩的思路与代码

2016-8-29 13:23| 发布者: zhangjf| 查看: 674| 评论: 0

摘要: 本文实例为大家分享了java实现图片压缩的相关代码,供大家参考,具体内容如下 import java.awt.Image;import java.awt.image.BufferedImage;import java.io.ByteArrayOutputStream;import java.io.IOException;impor ...

本文实例为大家分享了java实现图片压缩的相关代码,供大家参考,具体内容如下

  1. import java.awt.Image;
  2. import java.awt.image.BufferedImage;
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import javax.imageio.ImageIO;
  7. public class ImageProcess {
  8. /**
  9. * 图片
  10. */
  11. private Image img;
  12. /**
  13. * 宽度
  14. */
  15. private int width;
  16. /**
  17. * 高度
  18. */
  19. private int height;
  20. /**
  21. * 文件格式
  22. */
  23. private String imageFormat;
  24. /**
  25. * 构造函数
  26. * @throws Exception
  27. */
  28. public ImageProcess(InputStream in,String fileName) throws Exception{
  29. //构造Image对象
  30. img = ImageIO.read(in);
  31. //得到源图宽
  32. width = img.getWidth(null);
  33. //得到源图长
  34. height = img.getHeight(null);
  35. //文件格式
  36. imageFormat = fileName.substring(fileName.lastIndexOf(".")+1);
  37. }
  38. /**
  39. * 按照宽度还是高度进行压缩
  40. * @param w int 最大宽度
  41. * @param h int 最大高度
  42. */
  43. public byte[] resizeFix(int w, int h) throws IOException {
  44. if (width / height > w / h) {
  45. return resizeByWidth(w);
  46. } else {
  47. return resizeByHeight(h);
  48. }
  49. }
  50. /**
  51. * 以宽度为基准,等比例放缩图片
  52. * @param w int 新宽度
  53. */
  54. public byte[] resizeByWidth(int w) throws IOException {
  55. int h = (int) (height * w / width);
  56. return resize(w, h);
  57. }
  58. /**
  59. * 以高度为基准,等比例缩放图片
  60. * @param h int 新高度
  61. */
  62. public byte[] resizeByHeight(int h) throws IOException {
  63. int w = (int) (width * h / height);
  64. return resize(w, h);
  65. }
  66. /**
  67. * 强制压缩/放大图片到固定的大小
  68. * @param w int 新宽度
  69. * @param h int 新高度
  70. */
  71. public byte[] resize(int w, int h) throws IOException {
  72. // SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢
  73. BufferedImage image = new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB );
  74. image.getGraphics().drawImage(img, 0, 0, w, h, null); // 绘制缩小后的图
  75. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  76. ImageIO.write(image, imageFormat, baos);
  77. return baos.toByteArray();
  78. }
  79. }
复制代码

以上就是本文的全部内容,希望对大家的学习有所帮助,轻松实现图片压缩操作。

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-7-7 02:37

Copyright 2015-2025 djqfx

返回顶部