java后台图片大小压缩
2016-02-17 15:50
399 查看
现在像素越来越高,图片越来越大,但是有时我们保存到服务器上的图片并不需要这么大.占用服务器资源不说,每回调阅查看时还浪费流量,所以就需要在存照片进服务器的时候进行下图片的压缩.
废话不多说,上代码:
//可以设置个图片工具类,需要时间调用其中的方法.
public class PicUtil {
/**
* 压缩照片
* @return
* @throws IOException
*/
public static void compressPhoto (String newFullPath) throws IOException{
//压缩处理
File oldfile = new File(newFullPath);
BufferedImage image = ImageIO.read(oldfile);
int srcWidth = image.getWidth(null);//得到文件原始宽度
int srcHeight = image.getHeight(null);//得到文件原始高度
int newWidth =1000;
double scale_w = (double) newWidth / srcWidth;
int newHeight = (int) (srcHeight * scale_w);
BufferedImage newImage = new BufferedImage(newWidth, newHeight,
BufferedImage.TYPE_INT_RGB);
newImage.getGraphics().drawImage(image.getScaledInstance(newWidth, newHeight,
Image.SCALE_SMOOTH), 0, 0, null);
ImageIO.write(newImage, "jpg",new File(newFullPath));
}
}
废话不多说,上代码:
//可以设置个图片工具类,需要时间调用其中的方法.
public class PicUtil {
/**
* 压缩照片
* @return
* @throws IOException
*/
public static void compressPhoto (String newFullPath) throws IOException{
//压缩处理
File oldfile = new File(newFullPath);
BufferedImage image = ImageIO.read(oldfile);
int srcWidth = image.getWidth(null);//得到文件原始宽度
int srcHeight = image.getHeight(null);//得到文件原始高度
int newWidth =1000;
double scale_w = (double) newWidth / srcWidth;
int newHeight = (int) (srcHeight * scale_w);
BufferedImage newImage = new BufferedImage(newWidth, newHeight,
BufferedImage.TYPE_INT_RGB);
newImage.getGraphics().drawImage(image.getScaledInstance(newWidth, newHeight,
Image.SCALE_SMOOTH), 0, 0, null);
ImageIO.write(newImage, "jpg",new File(newFullPath));
}
}
相关文章推荐
- Java学习笔记2016.2.17 方法参数传递
- JList监听,选择会得到两次事件
- java连接sqlserver
- Eclipse搭建SSH(Struts2+Spring3+Hibernate3)开发项目
- 彻底解决Spring MVC 中文乱码 问题
- Hibernate反向工程-——Myeclipse从数据库反向生成Java类
- JAVA字符串格式化-String.format()的使用
- Java JVM:垃圾回收问题
- SpringMVC 初探--前言
- java连接PostgreSQL数据库出现问题
- JAVA实现基础排序算法
- struts Value Stack 值栈
- Spring项目搭建
- JVM调优-Java垃圾回收之分代回收
- jdk配置、jvm配置、远程debug配置样例
- eclipse保错解决
- Spring AOP中pointcut expression表达式解析 及匹配多个条件
- Exception in thread "main" java.net.BindException: Address already in use: JVM_Bind
- Exception in thread "main" java.net.BindException: Address already in use: JVM_Bind
- 序列求和