首页 > 代码库 > 制作缩略图
制作缩略图
package com.huawei.utils;
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;
/**
* @author Administrator
*
*/
public class ImageUtil {
//“相框”的宽高
private static final int WIDTH=300;
private static final int HEIGHT=200;
public static void preview(File src,File out,String format) throws Exception{
//将文件 映射到内存中
BufferedImage image = ImageIO.read(src);
//得到原始图片的宽高
int height = image.getHeight();
int width = image.getWidth();
//计算目标图片的宽高
int x = WIDTH;
int y = HEIGHT;
if(width*y>height*x){
y = height*x/width;
}
if(width*y<height*x){
x = width*y/height;
}
System.out.println(width);
System.out.println(height);
System.out.println(width*1.0/height);
System.out.println(x);
System.out.println(y);
System.out.println(x*1.0/y);
//是相框
BufferedImage new_Image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.SCALE_SMOOTH);
//创建画笔
Graphics2D graphics2d = new_Image.createGraphics();
//设置白色
graphics2d.setColor(new Color(255, 255, 255));
//填充颜色
graphics2d.fillRect(0, 0, WIDTH, HEIGHT);
//得到缩放以后的图片
Image target = image.getScaledInstance(x, y, BufferedImage.SCALE_SMOOTH);
graphics2d.drawImage(target, (WIDTH-x)/2, (HEIGHT-y)/2, x, y, null);
ImageIO.write(new_Image, format, out);
}
public static void main(String[] args) throws Exception{
preview(new File("D:/bg.jpg"),new File("D:/bg1.jpg"),"jpg");
}
}
制作缩略图