图片指定压缩大小
import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.UUID; /** * 图片压缩 */ public class ImageCompressUtil { private static String path = "C:\\Users\\Administrator\\Pictures\\"; public static void main(String[] args) throws IOException { File imageFile = new File(path + "反.jpg"); BufferedImage inputImage = ImageIO.read(imageFile); //通过比例压缩 float scale = 0.5f; BufferedImage outputImage = compress(inputImage, scale); //图片输出路径,以及图片名 File outputFile = new File(path + UUID.randomUUID() + "." + getImageType(inputImage.getType())); ImageIO.write(outputImage, getImageType(inputImage.getType()), outputFile); } /** * 压缩图片 */ public static BufferedImage compress(BufferedImage inputImage, float scale) { //压缩之后的长度和宽度 int outputHeight = (int) (inputImage.getHeight() * scale); int outputWidth = (int) (inputImage.getWidth() * scale); BufferedImage outputImage = new BufferedImage(outputWidth, outputHeight, inputImage.getType()); outputImage.getGraphics().drawImage( inputImage.getScaledInstance(outputWidth, outputHeight, Image.SCALE_SMOOTH), 0, 0, null); return outputImage; } public static String getImageType(int imageType) { switch (imageType) { // case 5: // return "jpg"; case 6: return "png"; case 13: return "gif"; default: return "jpg"; } }
//根据路劲获取大小
private static BufferedImage getBufferedImage(String imgUrl) {
URL url = null;
InputStream is = null;
BufferedImage img = null;
try {
url = new URL(imgUrl);
is = url.openStream();
img = ImageIO.read(is);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return img;
}
public static ImageInfo getImgInfo(String url) {
ImageInfo imageInfo = new ImageInfo();
BufferedImage image = getBufferedImage(url);
if (image != null) {
logger.info("图片高度:" + image.getHeight());
logger.info("图片宽度:" + image.getWidth());
imageInfo.setHeight(image.getHeight());
imageInfo.setWidth(image.getWidth());
imageInfo.setUrl(url);
return imageInfo;
}
return null;
}
人这辈子没法做太多事情,所以每做一件事都要做到精彩绝伦。
因为,这就是我的宿命。人生苦短,你明白吗?
所以这是我为人生做出的选择