Java上传头像时进行等比缩放

以下为详细代码

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import javax.imageio.ImageIO;

public class UploadHead {

/**
* @param file 文件流
* @param path 文件存放路径
* @param userId 上传用户的Id
* @return 新文件名
* @throws Exception
*/
public static String uploadHead(File file, String path, int userId) throws Exception {

String nowTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());//当前时间
Random r = new Random();
int x = r.nextInt(999999); //生成一个随机数
String newFileName = userId+"-"+x+"-"+nowTime+".jpg";//得到文件的新名字

FileInputStream is = new FileInputStream(file);
BufferedImage sourceImg = javax.imageio.ImageIO.read(is);

int width = sourceImg.getWidth(); //原文件宽度
int height = sourceImg.getHeight(); //原文件高度

if(width>200||height>200){ //等比缩放为200*200的图片,如果宽和高有一个大于200的就进行截取
DecimalFormat df=new DecimalFormat("0.000");

double bili = 0.000; //计算等比

if(width > height){ //根据像素大的一方进行等比缩放
bili = Double.parseDouble(df.format(width / 200.0));
}else{
bili = Double.parseDouble(df.format(height / 200.0));
}
width = (int) (width / bili);
height = (int) (height / bili);
}

BufferedImage src = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //根据计算好的宽高新建画布

src.getGraphics().drawImage(sourceImg.getScaledInstance(width, height,Image.SCALE_SMOOTH), 0, 0, null);

ImageIO.write(src, "JPEG", new File(path,newFileName)); //输出图像
is.close();
return newFileName ;
}
}



[color=red][size=medium]有什么不妥的地方,欢迎留言纠错![/size][/color]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值