有一个宽450像素,高450像素的图像。我想将此图像转换为75 x 75像素。我怎么能这样做?
答案 0 :(得分:4)
BufferedImage scaledImg = new BufferedImage(75, 75, BufferedImage.TYPE_INT_RGB);
scaledImg.createGraphics().drawImage(sourceImg, 0, 0, 75, 75, null);
答案 1 :(得分:1)
来自How to resize an image in Java?
public class ImageResize {
private static final int IMG_WIDTH = 75;
private static final int IMG_HEIGHT = 75;
public static void main(String [] args){
try{
BufferedImage originalImage = ImageIO.read(new File("c:\\image\\img1.jpg"));
int type = originalImage.getType() == 0? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
BufferedImage resizeImageJpg = resizeImage(originalImage, type);
ImageIO.write(resizeImageJpg, "jpg", new File("c:\\image\\img1_jpg.jpg"));
BufferedImage resizeImagePng = resizeImage(originalImage, type);
ImageIO.write(resizeImagePng, "png", new File("c:\\image\\img1_png.jpg"));
BufferedImage resizeImageHintJpg = resizeImageWithHint(originalImage, type);
ImageIO.write(resizeImageHintJpg, "jpg", new File("c:\\image\\img1_hint_jpg.jpg"));
BufferedImage resizeImageHintPng = resizeImageWithHint(originalImage, type);
ImageIO.write(resizeImageHintPng, "png", new File("c:\\image\\img1_hint_png.jpg"));
}catch(IOException e){
System.out.println(e.getMessage());
}
}
private static BufferedImage resizeImage(BufferedImage originalImage, int type){
BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
g.dispose();
return resizedImage;
}
private static BufferedImage resizeImageWithHint(BufferedImage originalImage, int type){
BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, 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;
}
}