is it possible to keep the image quality when resize it in java? this is my code:
package com.example.demo;
import lombok.extern.slf4j.Slf4j;
import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
@Slf4j
public class DemoApplicationSlim {
public static void main(String[] args) throws Exception {
String filePath = "/Users/john/Downloads/zj/test.jpeg";
Path path = Paths.get(filePath);
byte[] bytes = Files.readAllBytes(path);
String base64Origin = Base64.getEncoder().encodeToString(bytes);
BufferedImage resizedIdPhoto = new BufferedImage(300, 400, BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics = resizedIdPhoto.createGraphics();
BufferedImage img = Base64ToBufferImage(base64Origin);
graphics.drawImage(img, 0, 0, 300, 400, null);
String b64Resize = bufferImageToBase64(resizedIdPhoto, "png");
saveImage(base64Origin,"/Users/john/Downloads/hr-origin.jpeg");
saveImage(b64Resize,"/Users/john/Downloads/hr-resize.jpeg");
}
private static void saveImage(String base64Image, String imagePath) {
try {
byte[] imageBytes = Base64Coder.decode(base64Image);
File imageFile = new File(imagePath);
if (!imageFile.exists()) {
imageFile.createNewFile();
}
FileOutputStream outputStream = new FileOutputStream(imageFile);
outputStream.write(imageBytes);
outputStream.flush();
outputStream.close();
System.out.println("save success:" + imagePath);
} catch (IOException e) {
log.error("save file failed",e);
}
}
public static BufferedImage Base64ToBufferImage(String base64) {
BufferedImage image = null;
byte[] imageBytes;
imageBytes = Base64.getDecoder().decode(base64);
try (ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes)) {
image = ImageIO.read(bis);
} catch (IOException ex) {
log.error("read image error", ex);
}
return image;
}
public static String bufferImageToBase64(BufferedImage image, String format) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
javax.imageio.ImageIO.write(image, format, baos);
byte[] bytes = baos.toByteArray();
String base64 = Base64.getEncoder().encodeToString(bytes);
return base64;
}
}
now I found a issue it that when I resized the image, the resized output image loss so much quality. is it possible to keep original quality when resize? I have found this lib https://github.com/rkalla/imgscalr but it stop maintain for 5 years.