81,094
社区成员
发帖
与我相关
我的任务
分享
public static void scale(String srcImageFile, String result, int reswidth, int resheight) {
try {
BufferedImage src = ImageIO.read(new File(srcImageFile)); // 读入文件
int width = src.getWidth(); // 得到源图宽
int height = src.getHeight(); // 得到源图长
int scaleNum = 0; //缩放比例
int scaledWidth = 0; //缩放后的宽
int scaledHeight = 0; //缩放后的高
int x = 0;
int y = 0;
if(reswidth>0&&resheight>0&&(width>reswidth||height>resheight)){
if(height>=width){
scaleNum = height / resheight;
}else if(width>height){
scaleNum = width / reswidth;
}
scaledWidth = width / scaleNum;
scaledHeight = height / scaleNum;
}else{
scaledWidth = width;
scaledHeight = height;
}
x = (reswidth-scaledWidth)/2;
y = (resheight-scaledHeight)/2;
System.out.println("width :"+width+" height :"+height);
System.out.println("scaledWidth :"+scaledWidth+" scaledHeight :"+scaledHeight);
System.out.println("reswidth :"+reswidth+" resheight :"+resheight);
Image image = src.getScaledInstance(scaledWidth, scaledHeight, Image.SCALE_DEFAULT);
BufferedImage tag = new BufferedImage(reswidth, resheight, BufferedImage.TYPE_INT_RGB);
Graphics2D g = tag.createGraphics();
g.setBackground(Color.WHITE);
g.clearRect(0,0,reswidth, resheight);
g.drawImage(image, x<0?0:x, y<0?0:y, null); // 绘制缩小后的图
g.dispose();
ImageIO.write(tag, "JPEG", new File(result));// 输出到文件流
} catch (IOException e) {
e.printStackTrace();
}
}