import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageTool {
public static final int WIDTH = 240;
public static final int HEIGTH = 240;
public static void getPreviewImage(File source, File destImage, String format){
try {
BufferedImage bufferedImage = ImageIO.read(source);
BufferedImage image = new BufferedImage(WIDTH, HEIGTH, BufferedImage.TYPE_INT_RGB);
//创建缩放后的画布 TYPE_INT_RGB是具有合成整数像素的 8 位 RGB 颜色分量
int x = bufferedImage.getWidth();
int y = bufferedImage.getHeight();
int x1 = WIDTH;
int y1 = HEIGTH;
if(WIDTH*y<HEIGTH*x){ //高度不够
y1 = WIDTH*y/x;
}
if(WIDTH*y<HEIGTH*x){ //宽度不够
x1 = HEIGTH*x/y;
}
Graphics2D graphics2d = image.createGraphics();
graphics2d.setColor(new Color(255,255,255));
graphics2d.fillRect(0, 0, WIDTH, HEIGTH);
Image image2 = bufferedImage.getScaledInstance(x1, y1, bufferedImage.SCALE_SMOOTH);
graphics2d.drawImage(image2, (WIDTH-x1)/2, (HEIGTH-y1)/2, null);
ImageIO.write(image, format, destImage);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
getPreviewImage(new File("e:/re.png"),new File("e:/aa.jpg"),"jpg");
}
}