您的位置:首页 > 编程语言 > Java开发

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

        

            }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: