1. 程式人生 > 實用技巧 >springboot上傳圖片後儲存到本地

springboot上傳圖片後儲存到本地

MultipartFile bannerPicture    用於接收圖片的引數
bannerPicture.getBytes();
pictureName = Util.uuid() + "." + Constants.PICTURE_FORMAT; //隨機圖片名
Path path = Paths.get(Constants.BANNER_PICTURE_STORE_PATH, pictureName);//儲存圖片地址

/**
* 將圖片儲在指定路徑
*
* @param picture 圖片
* @param path 儲存路徑
*/
public static void savePicture(byte[] picture, Path path) {
if (Objects.isNull(picture) || Objects.isNull(path)) {
log.error("can not save picture for path:{}", path);
return;
}


try (InputStream in = new ByteArrayInputStream(picture)) {
BufferedImage input = ImageIO.read(in);
int width = input.getWidth();
int height = input.getHeight();

BufferedImage output = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
int[] px = new int[width * height];
input.getRGB(0, 0, width, height, px, 0, width);
output.setRGB(0, 0, width, height, px, 0, width);
  ImageIO.write(output, Constants.PICTURE_FORMAT, path.toFile()); //PICTURE_FORMAT= "jpg"
    } catch (IOException e) {
log.error("set user picture failed! path:{}", path, e);
}
}