I made multiple image uploading code in Java. It will resize image if it's too big.
Everything seems to work fine, but uploaded .gif files do not move.
I think I mixed multipartFile and imageIO. It also seems like contenttype code has a problem.
I don't know where to fix.
public class FileHandler {
private static final int MAX_WIDTH = 780;
private static final int MAX_HEIGHT = 1000;
public List<ImageModel> parseFileInfo(String boardType, List<MultipartFile> multipartFiles) throws Exception {
List<ImageModel> fileList = new ArrayList<>();
if (multipartFiles.isEmpty()) {
return fileList;
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
String current_date = simpleDateFormat.format(new Date());
String absolutePath = new File("").getAbsolutePath() + "\\src\\main\\";
String path = "uploads/images/" + boardType + "/" + current_date;
File file = new File(absolutePath + path);
if (!file.exists()) {
file.mkdirs();
}
for (MultipartFile multipartFile : multipartFiles) {
if (!multipartFile.isEmpty()) {
BufferedImage originalImage = ImageIO.read(multipartFile.getInputStream());
int contentType = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
String[] originalName = multipartFile.getOriginalFilename().split("\\.");
String Type = originalName[1];
int width = originalImage.getWidth();
int height = originalImage.getHeight();
Dimension imgSize = new Dimension(width, height);
Dimension boundary = new Dimension(MAX_WIDTH, MAX_HEIGHT);
Dimension newImgSize = getScaledDimension(imgSize, boundary);
Image resizedImage = originalImage.getScaledInstance(newImgSize.width, newImgSize.height, Image.SCALE_SMOOTH);
BufferedImage newImage = new BufferedImage(newImgSize.width, newImgSize.height, BufferedImage.TYPE_INT_BGR);
Graphics graphics = newImage.getGraphics();
graphics.drawImage(resizedImage, 0, 0, null);
graphics.dispose();
String new_file_name = System.nanoTime() + "." + Type;
file = new File(absolutePath + path + "/" + new_file_name);
try{
ImageIO.write(newImage, Type, file);
}catch (IOException e) {
throw new RuntimeException(e);
}
}
}
return fileList;
}
}