一、ImgaeHelper类,对图片压缩,返回BufferedImage
package com.ruoyi.common.utils;
import org.junit.jupiter.api.Test;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.io.*;
/**
* 图片工具类,完成图片的截取
* 所有方法返回值均未boolean型
*/
public class ImageHelper {
/**
* 实现图像的等比缩放
* @param source
* @param targetW
* @param targetH
* @return
*/
private static BufferedImage resize(BufferedImage source, int targetW,
int targetH) {
// targetW,targetH分别表示目标长和宽
int type = source.getType();
BufferedImage target = null;
double sx = (double) targetW / source.getWidth();
double sy = (double) targetH / source.getHeight();
// 这里想实现在targetW,targetH范围内实现等比缩放。如果不需要等比缩放
// 则将下面的if else语句注释即可
if (sx < sy) {
sx = sy;
targetW = (int) (sx * source.getWidth());
} else {
sy = sx;
targetH = (int) (sy * source.getHeight());
}
if (type == BufferedImage.TYPE_CUSTOM) { // handmade
ColorModel cm = source.getColorModel();
WritableRaster raster = cm.createCompatibleWritableRaster(targetW,
targetH);
boolean alphaPremultiplied = cm.isAlphaPremultiplied();
target = new BufferedImage(cm, raster, alphaPremultiplied, null);
} else
target = new BufferedImage(targetW, targetH, type);
Graphics2D g = target.createGraphics();
// smoother than exlax:
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
g.dispose();
return target;
}
/**
* 实现图像的等比缩放和缩放后的截取, 处理成功返回true, 否则返回false
* @param inFilePath 要截取文件的路径
* @param outFilePath 截取后输出的路径
* @param width 要截取宽度
* @param hight 要截取的高度
* @throws Exception
*/
public static boolean compress(String inFilePath, String outFilePath,
int width, int hight) {
boolean ret = false;
File file = new File(inFilePath);
File saveFile = new File(outFilePath);
InputStream in = null;
try {
in = new FileInputStream(file);
ret = compress(in, saveFile, width, hight);
} catch (FileNotFoundException e) {
e.printStackTrace();
ret = false;
} finally{
if(null != in){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return ret;
}
/**
* 实现图像的等比缩放和缩放后的截取, 处理成功返回true, 否则返回false
* @param in 要截取文件流
* @param outFilePath 截取后输出的路径
* @param width 要截取宽度
* @param hight 要截取的高度
* @throws Exception
*/
public static boolean compress(InputStream in, File saveFile,
int width, int hight) {
// boolean ret = false;
BufferedImage srcImage = null;
try {
srcImage = ImageIO.read(in);
} catch (IOException e) {