I need to resize an image to 100*100 Aspect ratio in order to create an icon. i am using java.awt.Graphics2D
for the same.
import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class FileResizeService {
public File resizeImage(File file, String fileExtension) throws IOException {
int imageWidth=100;
int imageHeight=100;
BufferedImage originalImage = ImageIO.read(file);
int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
BufferedImage drawImage = drawImage(originalImage, type, imageWidth, imageHeight);
ImageIO.write(drawImage, fileExtension, file);
return file;
}
private BufferedImage drawImage(BufferedImage originalImage, int type, int imageWidth, int imageHeight) {
BufferedImage resizedImage = new BufferedImage(imageWidth, imageHeight, type);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, imageWidth, imageHeight, null);
g.dispose();
g.setComposite(AlphaComposite.Src);
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
return resizedImage;
}
}
Above code resizes a high resolution image of size 5mb to an image of 100*100 aspect ratio, but the image size still remains the same(i.e., 5mb in this case), which is too much for an icon. i want the resized image to be in some kilobytes.
Am i missing something ?