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=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; } }