springboot控制层代码如下:
@PostMapping("upload")
public Result<String> uploadImage(MultipartFile file){
String imagePath = UploadImageUtil.uploadImage(file);
}
图片上传函数
/**
* 上传图片函数
* @param file 图片文件
* @return
*/
public static String uploadImage(MultipartFile file){
// 获取唯一的uuid
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
try {
// 获取图片存储的完整路径
String path1 = URLDecoder.decode((ResourceUtils.getURL("classpath:").getPath()+"static/img/"), System.getProperty("file.encoding"));
String imagePath = path1 + uuid + ".jpg";
// 获取要上传图片的目录,同时解码
File imageFolder = new File(URLDecoder.decode(path1, System.getProperty("file.encoding")));
// new一个图片文件
File fileImage = new File(imageFolder, uuid + ".jpg");
if (!fileImage.getParentFile().exists()) {
// 如果不存在这个目录就创建一个目录
fileImage.getParentFile().mkdirs();
}
file.transferTo(fileImage);
BufferedImage img = ImageUtil.change2jpg(fileImage);
ImageIO.write(img, "jpg", fileImage);
// 返回图片的相对路径
return "/img/" + uuid + ".jpg";
}catch (Exception e){
e.printStackTrace();
// 上传图片失败就返回一个长度为0的空字符串
return "";
}
}
ImageUtil转换函数
public class ImageUtil {
public static BufferedImage change2jpg(File f) {
try {
Image i = Toolkit.getDefaultToolkit().createImage(f.getAbsolutePath());
PixelGrabber pg = new PixelGrabber(i, 0, 0, -1, -1, true);
pg.grabPixels();
int width = pg.getWidth(), height = pg.getHeight();
final int[] RGB_MASKS = { 0xFF0000, 0xFF00, 0xFF };
final ColorModel RGB_OPAQUE = new DirectColorModel(32, RGB_MASKS[0], RGB_MASKS[1], RGB_MASKS[2]);
DataBuffer buffer = new DataBufferInt((int[]) pg.getPixels(), pg.getWidth() * pg.getHeight());
WritableRaster raster = Raster.createPackedRaster(buffer, width, height, width, RGB_MASKS, null);
BufferedImage img = new BufferedImage(RGB_OPAQUE, raster, false, null);
return img;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public static void resizeImage(File srcFile, int width,int height, File destFile) {
try {
if(!destFile.getParentFile().exists()) {
destFile.getParentFile().mkdirs();
}
Image i = ImageIO.read(srcFile);
i = resizeImage(i, width, height);
ImageIO.write((RenderedImage) i, "jpg", destFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Image resizeImage(Image srcImage, int width, int height) {
try {
BufferedImage buffImg = null;
buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
buffImg.getGraphics().drawImage(srcImage.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
return buffImg;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}