java后台图片大小压缩

来源:互联网 发布:雷霆网络 倚天解压码 编辑:程序博客网 时间:2024/05/19 04:51

        现在像素越来越高,图片越来越大,但是有时我们保存到服务器上的图片并不需要这么大.占用服务器资源不说,每回调阅查看时还浪费流量,所以就需要在存照片进服务器的时候进行下图片的压缩.

        废话不多说,上代码:

      //可以设置个图片工具类,需要时间调用其中的方法.

       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));
        
            }

}


0 0
原创粉丝点击