liuxiaolong
2019-05-06 f99bc8c6a1d10610373738edd7d0aa0181c81d99
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
package com.cloud.user.utils;
 
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
 
import javax.imageio.ImageIO;
 
public class ImageUtils {
  /**
   * 如果图片超过规定尺寸,等比缩放图片
   * @author jiaojz
   * @param byteArray 原图片字节流
   * @param fileExtName 图片类型(后缀名)
   * @return 返回缩放后的图片字节流
   * @throws Exception
   */
  public static byte[] resize(byte[] byteArray,String fileExtName) throws Exception {
    
    BufferedImage image = ImageIO.read( new ByteArrayInputStream( byteArray ) );
    double width = image.getWidth();
    double height = image.getHeight();
    int nowWidth = 0;
    int nowHeight = 0;
    double widthRatio = 480/width;
    double heightRatio = 640/height;
    if(width>480&&height>640) {//如果宽高都大于规定大小
      if(widthRatio<heightRatio) {//如果宽比例小于高比例,就按照宽比例缩放
        nowWidth = (int) (width * widthRatio);
        nowHeight = (int) (height * widthRatio);
      }else {//否则按照高比例缩放
        nowWidth = (int) (width * heightRatio);
        nowHeight = (int) (height * heightRatio);
      }
    }else if(width>=480&&height<640) {//如果仅仅宽度大于规定大小,按照宽度缩放
      nowWidth = (int) (width * widthRatio);
      nowHeight = (int) (height * widthRatio);
    }else if(width<=480&&height>640) {//如果仅仅高度大于规定大小,按照高度缩放
      nowWidth = (int) (width * heightRatio);
      nowHeight = (int) (height * heightRatio);
    }else {
      return byteArray;
    }
    BufferedImage newImage = new BufferedImage(nowWidth, nowHeight,BufferedImage.TYPE_INT_RGB);
    Graphics g = newImage.getGraphics();
    g.drawImage(image, 0, 0, nowWidth, nowHeight, null);
    g.dispose();
    ByteArrayOutputStream out = new ByteArrayOutputStream();  
    ImageIO.write(image,fileExtName, out);  
    byte[] b = out.toByteArray();
    out.close();
    return b;
  }
}