从网络上获得一个图片,将他转变为缩略图(放大或缩小图片的宽高),然后再转换为MultipartFile对象 方便图片上传

/**
* @author gaoyang
* @create 2021-02-02 17:30
*/
public class ImageUtls {

/**
* 重新按比例设置图片的大小
* @param scale
* @param url
* @return
* @throws ImageFormatException
* @throws IOException
*/
public static MultipartFile resize(float scale, String url) throws ImageFormatException, IOException {
URL targetURL = new URL(url);
Image image = ImageIO.read(targetURL);
int[] size = getSize(scale, image);
return resize(size[0], size[1], url, image);
}

/**
* <b>function:</b> 将Image的宽度、高度缩放到指定width、height
*
* @param width 缩放的宽度
* @param height 缩放的高度
* @param url 图片地址
* @param targetImage 即将缩放的目标图片
* @return 分片文件
* @throws ImageFormatException
* @throws IOException
*/
public static MultipartFile resize(int width, int height, String url, Image targetImage) throws ImageFormatException, IOException {
width = Math.max(width, 1);
height = Math.max(height, 1);
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
image.getGraphics().drawImage(targetImage, 0, 0, width, height, null);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(image, url.substring(url.lastIndexOf(".") + 1), os);
InputStream is = new ByteArrayInputStream(os.toByteArray());
String[] split = url.split("/");
String name = split[split.length - 1];
MultipartFile multipartFile = new MockMultipartFile(name, name, "", is);
image.flush();
os.close();
is.close();
return multipartFile;
}

/**
* <b>function:</b> 通过指定的比例和图片对象,返回一个放大或缩小的宽度、高度
*
* @param scale 缩放比例
* @param image 图片对象
* @return 返回宽度、高度
* @author hoojo
* @createDate 2012-2-7 上午10:27:59
*/
public static int[] getSize(float scale, Image image) {
int targetWidth = image.getWidth(null);
int targetHeight = image.getHeight(null);
long standardWidth = Math.round(targetWidth * scale);
long standardHeight = Math.round(targetHeight * scale);
return new int[]{Integer.parseInt(Long.toString(standardWidth)), Integer.parseInt(String.valueOf(standardHeight))};
}

}
posted @ 2021-02-03 14:10  fangbao2008  阅读(250)  评论(0)    收藏  举报