gpt4 book ai didi

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

转载 作者:qq735679552 更新时间:2022-09-29 22:32:09 24 4
gpt4 key购买 nike

CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.

这篇CFSDN的博客文章java实现图片压缩的思路与代码由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.

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

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

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

最后此篇关于java实现图片压缩的思路与代码的文章就讲到这里了,如果你想了解更多关于java实现图片压缩的思路与代码的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com