JAVA开发之压缩图片并打成ZIP文件

引用

  JAVA 获取网络图片或本地图片压缩后打成ZIP,但是获取网络流存在问题:每次获取图片流的大小不一样(图片不完整),以致无法构建图片进行压缩? 

Java代码  收藏代码
  1. /* 
  2. 释以下代码:即可获取完整图片流网络不稳定情况且网络流是顺序读取,所以获得前部份流,不需要关闭连接,只需要将用完的流关闭即可 
  3. */  
  4. finally{  
  5.     if(httpCon != null)  
  6.     httpCon.disconnect();  
  7. }  

Java代码  收藏代码
  1. package com.sunshine.monitor.comm.util.http;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7. import java.io.OutputStream;  
  8. import java.net.HttpURLConnection;  
  9. import java.net.URL;  
  10. import java.net.URLConnection;  
  11. import java.util.Iterator;  
  12.   
  13. import javax.imageio.ImageIO;  
  14. import javax.imageio.ImageReader;  
  15. import javax.imageio.stream.ImageInputStream;  
  16.   
  17. import sun.net.www.protocol.ftp.FtpURLConnection;  
  18.   
  19. /** 
  20.  * 获取网络图片 
  21.  *  
  22.  * @author OY 
  23.  */  
  24. public abstract class HttpHelpers {  
  25.   
  26.     private static final String KEY = "file.encoding";  
  27.   
  28.     private static final String ENCODING = "GBK";  
  29.   
  30.     public static InputStream getInputStream(String url) throws Exception{  
  31.         URLConnection con = null;  
  32.         HttpURLConnection httpCon = null;  
  33.         FtpURLConnection ftpCon= null;  
  34.         try {  
  35.             System.setProperty(KEY, ENCODING);  
  36.             URL _url = new URL(url);  
  37.             con = _url.openConnection();  
  38.             con.setConnectTimeout(3000);  
  39.             con.setUseCaches(false);// 不缓存  
  40.             con.setDefaultUseCaches(false);  
  41.             if (con instanceof HttpURLConnection) {  
  42.                 httpCon = (HttpURLConnection) con;  
  43.                 httpCon.setInstanceFollowRedirects(true);  
  44.                 //httpCon.setRequestProperty("Accept-Charset", "utf-8");  
  45.                 if (httpCon.getResponseCode() >= 300) {  
  46.                     System.out.println("URL:" + url  
  47.                             + ",HTTP Request is not success, Response code is "  
  48.                             + httpCon.getResponseCode());  
  49.                 } else {  
  50.                     return httpCon.getInputStream();  
  51.                 }  
  52.             } else if(con instanceof FtpURLConnection){  
  53.                 ftpCon = (FtpURLConnection)con;  
  54.                 return ftpCon.getInputStream();  
  55.             }  
  56.         } catch (Exception e) {  
  57.             e.printStackTrace();  
  58.         }finally{  
  59.             if(httpCon != null)  
  60.                 httpCon.disconnect();  
  61.         }  
  62.         return null;  
  63.     }  
  64.       
  65.     public static void main(String[] args) {  
  66.         // 1图片本地存储大小  
  67.         OutputStream fout = null;  
  68.         InputStream input = null;  
  69.         try {  
  70.             fout = new FileOutputStream("F:" + File.separator + "1.jpg");  
  71.             input = getInputStream("http://192.168.1.200/t.jpg");  
  72.             byte[] buffer = new byte[1024];  
  73.             int count = 0 ;  
  74.             while((count=input.read(buffer)) != -1){  
  75.                 fout.write(buffer, 0, count);  
  76.             }  
  77.             fout.flush();  
  78.         } catch (Exception e) {  
  79.             e.printStackTrace();  
  80.         } finally{  
  81.             try {  
  82.                 if(input != null) input.close();  
  83.                 if(fout != null) fout.close();  
  84.             } catch (IOException e) {  
  85.                 e.printStackTrace();  
  86.             }  
  87.         }  
  88.           
  89.         // 2是否可以构建图片  
  90.         try {  
  91.             input = getInputStream("http://192.168.1.200/t.jpg");  
  92.             ImageInputStream iis = ImageIO.createImageInputStream(input);  
  93.             if(iis != null) {  
  94.                 Iterator<ImageReader> it = ImageIO.getImageReaders(iis);  
  95.                 if(!it.hasNext()){  
  96.                     System.out.println("流不完整或不是图片!");  
  97.                 } else {  
  98.                     System.out.println(it.next().getFormatName());  
  99.                 }  
  100.             }  
  101.         } catch (Exception e) {  
  102.             e.printStackTrace();  
  103.         }  
  104.     }  
  105. }  


引用

图片压缩采用thumbnailator,可以按大小、按比例、按质量压缩并增加水印,API简单 

Java代码  收藏代码
  1.  package com.sunshine.monitor.comm.util.compress;  
  2.   
  3. import java.io.ByteArrayInputStream;  
  4. import java.io.ByteArrayOutputStream;  
  5. import java.io.File;  
  6. import java.io.FileInputStream;  
  7. import java.io.IOException;  
  8. import java.io.InputStream;  
  9.   
  10. import javax.imageio.ImageIO;  
  11.   
  12. import net.coobird.thumbnailator.Thumbnails;  
  13. import net.coobird.thumbnailator.geometry.Positions;  
  14.   
  15. /** 
  16.  * 图片压缩:按大小、按比例压缩、按质量 
  17.  * 增加水印 
  18.  * @author OY 
  19.  *  
  20.  */  
  21. public abstract class CompressPictureTools {  
  22.   
  23.     private static float QUALITY = 0.6f;  
  24.       
  25.     /** 
  26.      * 按大小缩小 
  27.      *  
  28.      * @param file 
  29.      * @param width 
  30.      * @param height 
  31.      * @return 
  32.      * @throws Exception 
  33.      */  
  34.     public static byte[] compressOfSize(File file, int width, int height)  
  35.             throws Exception {  
  36.         byte[] bs = null;  
  37.         InputStream input = null;  
  38.         try {  
  39.             input = new FileInputStream(file);  
  40.             bs = compressOfSize(input, width, height);  
  41.         } catch (Exception e) {  
  42.             e.printStackTrace();  
  43.         } finally {  
  44.             try {  
  45.                 if (input != null)  
  46.                     input.close();  
  47.             } catch (IOException e) {  
  48.                 e.printStackTrace();  
  49.             }  
  50.         }  
  51.         return bs;  
  52.     }  
  53.   
  54.     /** 
  55.      * 按大小缩小 
  56.      *  
  57.      * @param input 原图 
  58.      * @param width 目标宽席 
  59.      * @param height 目标高度 
  60.      * @return 
  61.      * @throws Exception 
  62.      */  
  63.     public static byte[] compressOfSize(InputStream input, int width, int height)  
  64.             throws Exception {  
  65.         ByteArrayOutputStream output = null;  
  66.         try {  
  67.             output = new ByteArrayOutputStream();  
  68.             Thumbnails.of(input).size(width, height).toOutputStream(output);  
  69.             return output.toByteArray();  
  70.         } catch (IOException e) {  
  71.             e.printStackTrace();  
  72.         } finally {  
  73.             try {  
  74.                 if (output != null)  
  75.                     output.close();  
  76.             } catch (IOException e) {  
  77.                 e.printStackTrace();  
  78.             }  
  79.         }  
  80.         return null;  
  81.     }  
  82.   
  83.     /** 
  84.      * 按指定比例进行缩小和放大: percent=1不变 percent>1放大 percent<1缩小 
  85.      *  
  86.      * @param input 原图 
  87.      * @param percent 压缩比例 
  88.      * @return 
  89.      * @throws Exception 
  90.      */  
  91.     public static byte[] compressOfPercent(InputStream input, float percent)  
  92.             throws Exception {  
  93.         ByteArrayOutputStream output = null;  
  94.         try {  
  95.             output = new ByteArrayOutputStream();  
  96.             Thumbnails.of(input).scale(percent).toOutputStream(output);  
  97.             return output.toByteArray();  
  98.         } catch (Exception e) {  
  99.             e.printStackTrace();  
  100.         } finally {  
  101.             try {  
  102.                 if (output != null)  
  103.                     output.close();  
  104.             } catch (IOException e) {  
  105.                 e.printStackTrace();  
  106.             }  
  107.         }  
  108.         return null;  
  109.     }  
  110.   
  111.     /** 
  112.      * 按指定比例进行缩小和放大: percent=1不变 percent>1放大 percent<1缩小 
  113.      *  
  114.      * @param file 原图 
  115.      * @param percent 压缩比例 
  116.      */  
  117.     public static byte[] compressOfPercent(File file, float percent)  
  118.             throws Exception {  
  119.         byte[] bs = null;  
  120.         InputStream input = null;  
  121.         try {  
  122.             input = new FileInputStream(file);  
  123.             bs = compressOfPercent(input, percent);  
  124.         } catch (Exception e) {  
  125.             e.printStackTrace();  
  126.         } finally {  
  127.             try {  
  128.                 if (input != null)  
  129.                     input.close();  
  130.             } catch (IOException e) {  
  131.                 e.printStackTrace();  
  132.             }  
  133.         }  
  134.         return bs;  
  135.     }  
  136.   
  137.     /** 
  138.      * 按质量压缩:图片尺寸不变,压缩图片文件大小 
  139.      *  
  140.      * @param file 原图 
  141.      * @param quality 
  142.      *            =1为最高质量 
  143.      * @return 
  144.      * @throws Exception 
  145.      */  
  146.     public static byte[] compressOfQuality(File file, float quality)  
  147.             throws Exception {  
  148.         byte[] bs = null;  
  149.         InputStream input = null;  
  150.         try {  
  151.             input = new FileInputStream(file);  
  152.             bs = compressOfQuality(input, quality);  
  153.         } catch (Exception e) {  
  154.             e.printStackTrace();  
  155.         } finally {  
  156.             try {  
  157.                 if (input != null)  
  158.                     input.close();  
  159.             } catch (IOException e) {  
  160.                 e.printStackTrace();  
  161.             }  
  162.         }  
  163.         return bs;  
  164.     }  
  165.   
  166.     /** 
  167.      * 按质量压缩:图片尺寸不变,压缩图片文件大小 
  168.      *  
  169.      * @param input 原图 
  170.      * @param quality 
  171.      *            =1为最高质量 
  172.      * @return 
  173.      * @throws Exception 
  174.      */  
  175.     public static byte[] compressOfQuality(InputStream input, float quality)  
  176.             throws Exception {  
  177.         ByteArrayOutputStream output = null;  
  178.         try {  
  179.             output = new ByteArrayOutputStream();  
  180.             if(quality == 0){  
  181.                 Thumbnails.of(input).scale(1f).outputQuality(QUALITY)  
  182.                 .toOutputStream(output);  
  183.             } else {  
  184.                 Thumbnails.of(input).scale(1f).outputQuality(quality)  
  185.                     .toOutputStream(output);  
  186.             }  
  187.             return output.toByteArray();  
  188.         } catch (Exception e) {  
  189.             e.printStackTrace();  
  190.         } finally {  
  191.             try {  
  192.                 if (output != null)  
  193.                     output.close();  
  194.             } catch (IOException e) {  
  195.                 e.printStackTrace();  
  196.             }  
  197.         }  
  198.         return null;  
  199.     }  
  200.   
  201.     /** 
  202.      * 图片右下角添加水印 
  203.      *  
  204.      * @param fromPic 
  205.      *            原图 
  206.      * @param markPic 
  207.      *            水印图 
  208.      * @param transparent 
  209.      *            透明度 
  210.      * @return 
  211.      * @throws Exception 
  212.      */  
  213.     public static byte[] waterMark(byte[] fromPic, InputStream markPic,  
  214.             float transparent) throws Exception {  
  215.         InputStream finput = null;  
  216.         ByteArrayOutputStream output = null;  
  217.         try {  
  218.             finput = new ByteArrayInputStream(fromPic);  
  219.             output = new ByteArrayOutputStream();  
  220.             Thumbnails  
  221.                     .of(finput)  
  222.                     .scale(1f)  
  223.                     .watermark(Positions.BOTTOM_RIGHT, ImageIO.read(markPic),  
  224.                             transparent).toOutputStream(output);  
  225.             return output.toByteArray();  
  226.         } catch (Exception e) {  
  227.             e.printStackTrace();  
  228.         } finally {  
  229.             try {  
  230.                 if (output != null)  
  231.                     output.close();  
  232.                 if (finput != null)  
  233.                     finput.close();  
  234.             } catch (IOException e) {  
  235.                 e.printStackTrace();  
  236.             }  
  237.         }  
  238.         return null;  
  239.     }  
  240.   
  241.     /** 
  242.      * 图片格式转换 
  243.      *  
  244.      * @param fromPic 
  245.      *            原图 
  246.      * @param picFormat 
  247.      *            格式 png,jpg... 
  248.      * @return 
  249.      * @throws Exception 
  250.      */  
  251.     public static byte[] transferPicFormat(byte[] fromPic, String picFormat)  
  252.             throws Exception {  
  253.         ByteArrayInputStream finput = null;  
  254.         ByteArrayOutputStream output = null;  
  255.         try {  
  256.             finput = new ByteArrayInputStream(fromPic);  
  257.             output = new ByteArrayOutputStream();  
  258.             Thumbnails.of(finput).outputFormat(picFormat)  
  259.                     .toOutputStream(output);  
  260.             return output.toByteArray();  
  261.         } catch (Exception e) {  
  262.             e.printStackTrace();  
  263.         } finally {  
  264.             try {  
  265.                 if (output != null)  
  266.                     output.close();  
  267.                 if (finput != null)  
  268.                     finput.close();  
  269.             } catch (IOException e) {  
  270.                 e.printStackTrace();  
  271.             }  
  272.         }  
  273.         return null;  
  274.     }  
  275. }  

引用

因JDK1.7以下,不可以设置编码,以致中文乱码问题,未采用java.util.ZipOutputStream,而是Apache ant下的ZipOutputStream 

Java代码  收藏代码
  1. package com.sunshine.monitor.comm.util.compress;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.File;  
  5. import java.io.FileInputStream;  
  6. import java.io.IOException;  
  7. import java.io.InputStream;  
  8. import java.io.OutputStream;  
  9. import java.util.Arrays;  
  10. import java.util.Collections;  
  11. import java.util.Iterator;  
  12. import java.util.List;  
  13. import java.util.Map;  
  14. import java.util.Map.Entry;  
  15. import java.util.Set;  
  16.   
  17. import org.apache.tools.zip.ZipEntry;  
  18. import org.apache.tools.zip.ZipOutputStream;  
  19.   
  20. import com.sunshine.monitor.comm.util.http.HttpHelpers;  
  21. /** 
  22.  * 图片压缩成ZIP,支持并发多线程; 
  23.  * java.util.ZipOutputStream中文乱码  
  24.  * 方法一、JDK1.7可以设置编码  
  25.  * 方法二、换成Apache ant 
  26.  * @author OY 
  27.  *  
  28.  */  
  29. public class PicturePackZipTools {  
  30.   
  31. private static String DEFAULT_COMPRESS_ENCODE = "GBK";  
  32.       
  33.     private static ZipOutputStream getZipStreamEncode(OutputStream output,  
  34.             String encode) {  
  35.         ZipOutputStream zipStream = new ZipOutputStream(output);  
  36.         if (encode == null || "".equals(encode)) {  
  37.             zipStream.setEncoding(DEFAULT_COMPRESS_ENCODE);  
  38.         } else {  
  39.             zipStream.setEncoding(encode);  
  40.         }  
  41.         return zipStream;  
  42.     }  
  43.   
  44.     /** 
  45.      * 访问本地路径下的所有文件 
  46.      *  
  47.      * @param path 
  48.      * @return 
  49.      */  
  50.     public static List<File> loadFiles(String path) {  
  51.         List<File> list = null;  
  52.         try {  
  53.             File fold = new File(path);  
  54.             if (fold.isDirectory()) {  
  55.                 File[] files = fold.listFiles();  
  56.                 list = Arrays.asList(files);  
  57.             }  
  58.         } catch (Exception e) {  
  59.             e.printStackTrace();  
  60.         }  
  61.         return list;  
  62.     }  
  63.   
  64.     /** 
  65.      * 读取本地系统路径下的所有图片打成ZIP 
  66.      *  
  67.      * @param path 
  68.      * @param output 
  69.      * @param compress 
  70.      */  
  71.     public static void compressZip(String path, OutputStream output,  
  72.             String encode, boolean compress) {  
  73.         List<File> listfiles = null;  
  74.         ZipOutputStream zipStream = null;  
  75.         try {  
  76.             zipStream = getZipStreamEncode(output, encode);  
  77.             listfiles = loadFiles(path);  
  78.             for (File file : listfiles) {  
  79.                 compressZip(file, zipStream, compress);  
  80.             }  
  81.         } catch (Exception e) {  
  82.             e.printStackTrace();  
  83.         } finally {  
  84.             try {  
  85.                 if (zipStream != null) {  
  86.                     zipStream.close();  
  87.                 }  
  88.             } catch (IOException e) {  
  89.                 e.printStackTrace();  
  90.             }  
  91.         }  
  92.     }  
  93.   
  94.     /** 
  95.      * 读取网络图片打成打成ZIP 
  96.      * @param urls 
  97.      *            key = 图片名, value = 图片URL 
  98.      * @param output  
  99.      * @param encode 编码 
  100.      * @param compress 是否压缩 
  101.      */  
  102.     public static void compressZip(Map<String, String> urls,  
  103.             OutputStream output, String encode, boolean compress) {  
  104.         ZipOutputStream zipStream = null;  
  105.         try {  
  106.             zipStream = getZipStreamEncode(output, encode);  
  107.             Map<String, String> synUrls = Collections.synchronizedMap(urls);  
  108.             Set<Entry<String, String>> set = synUrls.entrySet();  
  109.             Iterator<Entry<String, String>> it = set.iterator();  
  110.             while (it.hasNext()) {  
  111.                 Entry<String, String> entry = it.next();  
  112.                 compressZip(entry.getValue(), zipStream, entry.getKey(),  
  113.                         compress);  
  114.             }  
  115.         } catch (Exception e) {  
  116.             e.printStackTrace();  
  117.         } finally {  
  118.             try {  
  119.                 if (zipStream != null) {  
  120.                     zipStream.close();  
  121.                 }  
  122.             } catch (IOException e) {  
  123.                 e.printStackTrace();  
  124.             }  
  125.         }  
  126.     }  
  127.   
  128.     /** 
  129.      * 压缩单个文件为ZIP 
  130.      * @param file 
  131.      * @param output 
  132.      * @param encode 
  133.      * @param compress 
  134.      */  
  135.     public static void compressZip(File file, OutputStream output,  
  136.             String encode, boolean compress) throws Exception{  
  137.         FileInputStream input = null;  
  138.         try {  
  139.             input = new FileInputStream(file);  
  140.             compressZip(input,file.getName(),output,encode,compress);  
  141.         } catch (Exception e) {  
  142.             e.printStackTrace();  
  143.         }  finally {  
  144.             try {  
  145.                 if (input != null)  
  146.                     input.close();  
  147.             } catch (IOException e) {  
  148.                 e.printStackTrace();  
  149.             }  
  150.         }  
  151.           
  152.     }  
  153.   
  154.     /** 
  155.      * 压缩单个文件为ZIP 
  156.      * @param input 
  157.      * @param fileName 
  158.      * @param output 
  159.      * @param encode 
  160.      * @param compress 
  161.      */  
  162.     public static void compressZip(InputStream input, String fileName,  
  163.             OutputStream output, String encode, boolean compress) throws Exception {  
  164.         ZipOutputStream zipStream = null;  
  165.         try {  
  166.             zipStream = getZipStreamEncode(output, encode);  
  167.             zip(input, zipStream, fileName, compress);  
  168.         } catch (Exception e) {  
  169.             e.printStackTrace();  
  170.         } finally {  
  171.             try {  
  172.                 if (zipStream != null)  
  173.                     zipStream.close();  
  174.             } catch (IOException e) {  
  175.                 e.printStackTrace();  
  176.             }  
  177.         }  
  178.     }  
  179.   
  180.     /** 
  181.      * 本地图片 
  182.      */  
  183.     private static void compressZip(File file, ZipOutputStream zipStream,  
  184.             boolean compress) throws Exception{  
  185.         FileInputStream input = null;  
  186.         try {  
  187.             input = new FileInputStream(file);  
  188.             zip(input, zipStream, file.getName(), compress);  
  189.         } catch (Exception e) {  
  190.             e.printStackTrace();  
  191.         }finally{  
  192.             try {  
  193.                 if(input != null)  
  194.                     input.close();  
  195.             } catch (IOException e) {  
  196.                 e.printStackTrace();  
  197.             }  
  198.         }  
  199.     }  
  200.   
  201.     /** 
  202.      * 网络图片 
  203.      *  
  204.      * @param url 
  205.      * @param zipStream 
  206.      * @param compress 
  207.      */  
  208.     private static void compressZip(String url, ZipOutputStream zipStream,  
  209.             String fileName, boolean compress) throws Exception{  
  210.         InputStream input = null;  
  211.         try {  
  212.             input = HttpHelpers.getInputStream(url);  
  213.             zip(input, zipStream, fileName, compress);  
  214.         } catch (Exception e) {  
  215.             e.printStackTrace();  
  216.         } finally{  
  217.             try {  
  218.                 if(input != null)  
  219.                     input.close();  
  220.             } catch (IOException e) {  
  221.                 e.printStackTrace();  
  222.             }  
  223.         }  
  224.     }  
  225.   
  226.     /** 
  227.      * @param input 
  228.      * @param zipStream 
  229.      * @param zipEntryName 
  230.      * @param compress 
  231.      */  
  232.     private static void zip(InputStream input, ZipOutputStream zipStream,  
  233.             String zipEntryName, boolean compress) throws Exception{  
  234.         byte[] bytes = null;  
  235.         BufferedInputStream bufferStream = null;  
  236.         try {  
  237.             if(input == null)  
  238.                 throw new Exception("获取压缩的数据项失败! 数据项名为:" + zipEntryName);  
  239.             // 压缩条目不是具体独立的文件,而是压缩包文件列表中的列表项,称为条目,就像索引一样  
  240.             ZipEntry zipEntry = new ZipEntry(zipEntryName);  
  241.             // 定位到该压缩条目位置,开始写入文件到压缩包中  
  242.             zipStream.putNextEntry(zipEntry);  
  243.             if (compress) {  
  244.                 bytes = CompressPictureTools.compressOfQuality(input, 0);  
  245.                 zipStream.write(bytes, 0, bytes.length);  
  246.             } else {  
  247.                 bytes = new byte[1024 * 5];// 读写缓冲区  
  248.                 bufferStream = new BufferedInputStream(input);// 输入缓冲流  
  249.                 int read = 0;  
  250.                 while ((read = bufferStream.read(bytes)) != -1) {  
  251.                     zipStream.write(bytes, 0, read);  
  252.                 }  
  253.             }  
  254.         } catch (IOException e) {  
  255.             e.printStackTrace();  
  256.         } finally {  
  257.             try {  
  258.                 if (null != bufferStream)  
  259.                     bufferStream.close();  
  260.             } catch (IOException e) {  
  261.                 e.printStackTrace();  
  262.             }  
  263.         }  
  264.     }  
  265. }  
原文地址:https://www.cnblogs.com/xm1-ybtk/p/5112026.html