美文网首页
Java图片压缩处理

Java图片压缩处理

作者: 懂hyz | 来源:发表于2017-07-02 11:25 被阅读1744次

网页中某些图片大的时候,图片会加载慢,这时候需要对图片进行压缩处理,Java有对图片进行压缩处理的方法。

整体思路:

  1. 页面中显示图片(输出流-->访问本地磁盘上的某张图片)
  2. 访问的时候动态选择是否想要压缩某张图片(压缩判断)
  3. 把原始图片复制一份,复制出来的那份给压缩,页面中想要压缩的图片时,就访问压缩后的图片,否则,则显示原图
复制一张图片,输出在原路径下,返回新复制后的路径,修改了原始文件名。
/**
     * 把一个大图片copy一份出来作为压缩处理
     * @param oldFile
     * @return
     */
    public static String  copyFile(String oldFile){
        String outPath = null;
        try {
            int bytesum = 0; 
            int byteread = 0; 
            File oldfile = new File(oldFile); 
            if (oldfile.exists()) { //文件存在时 
            InputStream inStream = new FileInputStream(oldFile); //读入原文件
            int prefix = oldfile.getName().lastIndexOf("."); //取得后缀名的开始位数
            String afterPrefix = oldfile.getName().substring(prefix, oldfile.getName().length()); //原始的文件名的后缀名
            System.out.println("后缀名是: "+afterPrefix);
            String beforePrefix = oldfile.getName().substring(0, prefix); //原始的文件名的前缀名
            System.out.println("前缀名是: "+beforePrefix);
            System.out.println(oldfile.getParentFile());
            System.out.println(oldfile.getParent());
            outPath = oldfile.getParentFile()+"/"+beforePrefix+"_copy"+afterPrefix;
            System.out.println("======>  "+outPath);
            //将复制的新图片重新命名
            FileOutputStream fs = new FileOutputStream(outPath); 
            byte[] buffer = new byte[1444]; 
            int length; 
            while ( (byteread = inStream.read(buffer)) != -1) { 
            bytesum += byteread; //字节数 文件大小 
            fs.write(buffer, 0, byteread); 
            } 
            inStream.close(); 
            }
        } catch (FileNotFoundException e) {
            System.out.println("图片没找到!");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("复制图片出错!");
            e.printStackTrace();
        } 
        
        return outPath;
    }
把复制的出来的新图片进行压缩
/*** 
     * 功能 :按照正方形缩放图片,精度较高
     * 处理100X100或者别的
     * @param srcImgPath 原图片路径 
     * @param distImgPath  转换大小后图片路径 
     * @param width   转换后图片宽度 
     * @param height  转换后图片高度 
     */  
    public static void resizeImage(String srcImgPath, String distImgPath,int width, int height) throws IOException {  
        String subfix = "jpg";
        subfix = srcImgPath.substring(srcImgPath.lastIndexOf(".")+1,srcImgPath.length());
        File srcFile = new File(srcImgPath);  
        Image srcImg = ImageIO.read(srcFile);  
        BufferedImage buffImg = null; 
        if(subfix.equals("png") || subfix.equals("PNG")){
            buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        }else{
            buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        }
        Graphics2D graphics = buffImg.createGraphics();
        graphics.setBackground(Color.WHITE);
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, width, height);
        graphics.drawImage(srcImg.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);  
        ImageIO.write(buffImg, subfix, new File(distImgPath));  
    }
图片访问输出流,加标识符是否需要对图片进行压缩处理
/**
     * 查看一个图片
     * @param proNo
     * @param fileName
     * @param response
     */
    @RequestMapping("/image/{proNo}/{fileName}/{true}")
    public void image(@PathVariable("proNo") String proNo,
            @PathVariable("fileName") String fileName,
            @PathVariable("true") boolean resize,
            HttpServletResponse response){
        FileInputStream fis = null;
        StringBuffer sb = new StringBuffer(20);
        try {
//          fis = new FileInputStream("D:/stt/products/1611070030000029/2016110700300002964329.png");
            String imgPath = StringBufferUtil.append(sb, ManagerConf.getMangerConf().getProductSave(),"/",proNo,"/",fileName).toString();
            if(!FileUtil.fileExists(imgPath)){
                return;
            }
            System.out.println(resize);
            if(resize){ //首页过来的请求,执行压缩程序
                System.out.println("原图片的路径:==========>" + imgPath);
                System.out.println("执行复制图片开始:....");
                String nowPath = copyFile(imgPath);
                System.out.println("执行复制图片结束:....");
                System.out.println("新复制图片的路径为:=======>" + nowPath);
                System.out.println("开始压缩图片程序:....");
                resizeImage(nowPath, nowPath, 100, 100);
                System.out.println("开始压缩图片结束:....");
                ServletOutputStream os = response.getOutputStream();
                
                fis = new FileInputStream(nowPath);
                byte[] bs = new byte[fis.available()];
                fis.read(bs);
                os.write(bs);
            }else{
                ServletOutputStream os = response.getOutputStream();
                fis = new FileInputStream(imgPath);
                byte[] bs = new byte[fis.available()];
                fis.read(bs);
                os.write(bs);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                if(fis != null)fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
测试

这是URL最后标识符为true的时候,代表进行图片压缩。

压缩后

这是URL最后标识符为false的时候,图片未进行压缩处理。

压缩后

ok,到这里就完毕了。
我的博客文章地址:http://www.hanyz.cn/2017/06/28/Java%E5%9B%BE%E7%89%87%E5%8E%8B%E7%BC%A9%E5%A4%84%E7%90%86/

相关文章

  • 2.Java 图片质量压缩与图片缩放

    Java 图片压缩:像素质量压缩 、图片长宽缩放。常用方式:一种为Java有BufferedImage来处理;另一...

  • Java图片压缩处理

    网页中某些图片大的时候,图片会加载慢,这时候需要对图片进行压缩处理,Java有对图片进行压缩处理的方法。 整体思路...

  • 图片懒加载之高斯模糊

    压缩原始图片 将原始图片压缩至1~2kb甚至更小的图片nature.jpg 压缩 java 图片压缩natur...

  • iOS 图片压缩方法

    iOS 图片压缩方法 更多图片处理方法见图片组件 BBWebImage iOS 图片压缩方法 两种图片压缩方法 两...

  • 图片压缩处理

    @interface UIImage (fixOrientation)- (UIImage *)fixOrient...

  • UIIMageView高级处理

    一、图片压缩 1.1 直接格式转换压缩 1.2 Context重新绘制 二、图片处理 2.1 图片像素上修改 2....

  • Java图片压缩

    今天遇到了一个场景需要将图片压缩成480*640的格式,方便人脸检测,在网上搜到了Thumbnailator工具类...

  • 基于gulp的多页应用打包

    实现功能主要有 热加载,本地服务器,文件监听,动态刷新处理图片(优化图片,压缩)处理scss(压缩合并,兼容前缀,...

  • 图片上传处理 图片压缩

  • imageView的处理

    图片的处理参见谈谈 iOS 中图片的解压缩

网友评论

      本文标题:Java图片压缩处理

      本文链接:https://www.haomeiwen.com/subject/xduncxtx.html