如何用Java示例实现压缩图片并打包成ZIP文件的操作?
- 内容介绍
- 文章标签
- 相关推荐
本文共计1905个文字,预计阅读时间需要8分钟。
Java 获取网络或本地图片,压缩后打包成 ZIP,但获取网络流存在问题的解决方案:每次获取图片流的大小不一致(图片不完整),导致无法构建完整的图片进行压缩。以下是一种可能的解决方案代码:
javaimport java.io.*;import java.net.URL;import java.util.zip.ZipEntry;import java.util.zip.ZipOutputStream;
public class ImageCompressor { public static void main(String[] args) { String zipFile=output.zip; String[] imageUrls={ http://example.com/image1.jpg, http://example.com/image2.jpg // 更多图片 URL };
try (ZipOutputStream zos=new ZipOutputStream(new FileOutputStream(zipFile))) { for (String imageUrl : imageUrls) { byte[] imageBytes=getImageBytes(imageUrl); if (imageBytes !=null) { ZipEntry entry=new ZipEntry(imageUrl.substring(imageUrl.lastIndexOf(/) + 1)); zos.putNextEntry(entry); zos.write(imageBytes); zos.closeEntry(); } } } catch (IOException e) { e.printStackTrace(); } }
private static byte[] getImageBytes(String imageUrl) throws IOException { URL url=new URL(imageUrl); try (InputStream is=url.openStream()) { ByteArrayOutputStream buffer=new ByteArrayOutputStream(); int nRead; byte[] data=new byte[16384];
while ((nRead=is.read(data, 0, data.length)) !=-1) { buffer.write(data, 0, nRead); } buffer.flush(); return buffer.toByteArray(); } }}
这段代码首先定义了一个 `ImageCompressor` 类,其中包含一个 `main` 方法用于启动压缩过程。`getImageBytes` 方法用于从给定的 URL 获取图片的字节流。在 `main` 方法中,我们遍历图片 URL 数组,获取每个图片的字节流,并将其写入 ZIP 文件中。注意,这里假设每次获取的图片流是完整的,如果图片不完整,则需要进一步处理以确保获取到完整的图片数据。
JAVA 获取网络图片或本地图片压缩后打成ZIP,但是获取网络流存在问题:每次获取图片流的大小不一样(图片不完整),以致无法构建图片进行压缩?
/* 释以下代码:即可获取完整图片流网络不稳定情况且网络流是顺序读取,所以获得前部份流,不需要关闭连接,只需要将用完的流关闭即可 */ finally{ if(img.558idc.com/uploadfile/allimg/java/t.jpg"); byte[]buffer=newbyte[1024]; intcount=0; while((count=input.read(buffer))!=-1){ fout.write(buffer,0,count); } fout.flush(); }catch(Exceptione){ e.printStackTrace(); }finally{ try{ if(input!=null)input.close(); if(fout!=null)fout.close(); }catch(IOExceptione){ e.printStackTrace(); } } //2是否可以构建图片 try{ input=getInputStream("img.558idc.com/uploadfile/allimg/java/t.jpg"); ImageInputStreamiis=ImageIO.createImageInputStream(input); if(iis!=null){ Iterator<ImageReader>it=ImageIO.getImageReaders(iis); if(!it.hasNext()){ System.out.println("流不完整或不是图片!"); }else{ System.out.println(it.next().getFormatName()); } } }catch(Exceptione){ e.printStackTrace(); } } }
图片压缩采用thumbnailator,可以按大小、按比例、按质量压缩并增加水印,API简单
packagecom.sunshine.monitor.comm.util.compress; importjava.io.ByteArrayInputStream; importjava.io.ByteArrayOutputStream; importjava.io.File; importjava.io.FileInputStream; importjava.io.IOException; importjava.io.InputStream; importjavax.imageio.ImageIO; importnet.coobird.thumbnailator.Thumbnails; importnet.coobird.thumbnailator.geometry.Positions; /** *图片压缩:按大小、按比例压缩、按质量 *增加水印 *@authorOY * */ publicabstractclassCompressPictureTools{ privatestaticfloatQUALITY=0.6f; /** *按大小缩小 * *@paramfile *@paramwidth *@paramheight *@return *@throwsException */ publicstaticbyte[]compressOfSize(Filefile,intwidth,intheight) throwsException{ byte[]bs=null; InputStreaminput=null; try{ input=newFileInputStream(file); bs=compressOfSize(input,width,height); }catch(Exceptione){ e.printStackTrace(); }finally{ try{ if(input!=null) input.close(); }catch(IOExceptione){ e.printStackTrace(); } } returnbs; } /** *按大小缩小 * *@paraminput原图 *@paramwidth目标宽席 *@paramheight目标高度 *@return *@throwsException */ publicstaticbyte[]compressOfSize(InputStreaminput,intwidth,intheight) throwsException{ ByteArrayOutputStreamoutput=null; try{ output=newByteArrayOutputStream(); Thumbnails.of(input).size(width,height).toOutputStream(output); returnoutput.toByteArray(); }catch(IOExceptione){ e.printStackTrace(); }finally{ try{ if(output!=null) output.close(); }catch(IOExceptione){ e.printStackTrace(); } } returnnull; } /** *按指定比例进行缩小和放大:percent=1不变percent>1放大percent<1缩小 * *@paraminput原图 *@parampercent压缩比例 *@return *@throwsException */ publicstaticbyte[]compressOfPercent(InputStreaminput,floatpercent) throwsException{ ByteArrayOutputStreamoutput=null; try{ output=newByteArrayOutputStream(); Thumbnails.of(input).scale(percent).toOutputStream(output); returnoutput.toByteArray(); }catch(Exceptione){ e.printStackTrace(); }finally{ try{ if(output!=null) output.close(); }catch(IOExceptione){ e.printStackTrace(); } } returnnull; } /** *按指定比例进行缩小和放大:percent=1不变percent>1放大percent<1缩小 * *@paramfile原图 *@parampercent压缩比例 */ publicstaticbyte[]compressOfPercent(Filefile,floatpercent) throwsException{ byte[]bs=null; InputStreaminput=null; try{ input=newFileInputStream(file); bs=compressOfPercent(input,percent); }catch(Exceptione){ e.printStackTrace(); }finally{ try{ if(input!=null) input.close(); }catch(IOExceptione){ e.printStackTrace(); } } returnbs; } /** *按质量压缩:图片尺寸不变,压缩图片文件大小 * *@paramfile原图 *@paramquality *=1为最高质量 *@return *@throwsException */ publicstaticbyte[]compressOfQuality(Filefile,floatquality) throwsException{ byte[]bs=null; InputStreaminput=null; try{ input=newFileInputStream(file); bs=compressOfQuality(input,quality); }catch(Exceptione){ e.printStackTrace(); }finally{ try{ if(input!=null) input.close(); }catch(IOExceptione){ e.printStackTrace(); } } returnbs; } /** *按质量压缩:图片尺寸不变,压缩图片文件大小 * *@paraminput原图 *@paramquality *=1为最高质量 *@return *@throwsException */ publicstaticbyte[]compressOfQuality(InputStreaminput,floatquality) throwsException{ ByteArrayOutputStreamoutput=null; try{ output=newByteArrayOutputStream(); if(quality==0){ Thumbnails.of(input).scale(1f).outputQuality(QUALITY) .toOutputStream(output); }else{ Thumbnails.of(input).scale(1f).outputQuality(quality) .toOutputStream(output); } returnoutput.toByteArray(); }catch(Exceptione){ e.printStackTrace(); }finally{ try{ if(output!=null) output.close(); }catch(IOExceptione){ e.printStackTrace(); } } returnnull; } /** *图片右下角添加水印 * *@paramfromPic *原图 *@parammarkPic *水印图 *@paramtransparent *透明度 *@return *@throwsException */ publicstaticbyte[]waterMark(byte[]fromPic,InputStreammarkPic, floattransparent)throwsException{ InputStreamfinput=null; ByteArrayOutputStreamoutput=null; try{ finput=newByteArrayInputStream(fromPic); output=newByteArrayOutputStream(); Thumbnails .of(finput) .scale(1f) .watermark(Positions.BOTTOM_RIGHT,ImageIO.read(markPic), transparent).toOutputStream(output); returnoutput.toByteArray(); }catch(Exceptione){ e.printStackTrace(); }finally{ try{ if(output!=null) output.close(); if(finput!=null) finput.close(); }catch(IOExceptione){ e.printStackTrace(); } } returnnull; } /** *图片格式转换 * *@paramfromPic *原图 *@parampicFormat *格式png,jpg... *@return *@throwsException */ publicstaticbyte[]transferPicFormat(byte[]fromPic,StringpicFormat) throwsException{ ByteArrayInputStreamfinput=null; ByteArrayOutputStreamoutput=null; try{ finput=newByteArrayInputStream(fromPic); output=newByteArrayOutputStream(); Thumbnails.of(finput).outputFormat(picFormat) .toOutputStream(output); returnoutput.toByteArray(); }catch(Exceptione){ e.printStackTrace(); }finally{ try{ if(output!=null) output.close(); if(finput!=null) finput.close(); }catch(IOExceptione){ e.printStackTrace(); } } returnnull; } }
因JDK1.7以下,不可以设置编码,以致中文乱码问题,未采用java.util.ZipOutputStream,而是Apache ant下的ZipOutputStream
packagecom.sunshine.monitor.comm.util.compress; importjava.io.BufferedInputStream; importjava.io.File; importjava.io.FileInputStream; importjava.io.IOException; importjava.io.InputStream; importjava.io.OutputStream; importjava.util.Arrays; importjava.util.Collections; importjava.util.Iterator; importjava.util.List; importjava.util.Map; importjava.util.Map.Entry; importjava.util.Set; importorg.apache.tools.zip.ZipEntry; importorg.apache.tools.zip.ZipOutputStream; importcom.sunshine.monitor.comm.util.http.HttpHelpers; /** *图片压缩成ZIP,支持并发多线程; *java.util.ZipOutputStream中文乱码 *方法一、JDK1.7可以设置编码 *方法二、换成Apacheant *@authorOY * */ publicclassPicturePackZipTools{ privatestaticStringDEFAULT_COMPRESS_ENCODE="GBK"; privatestaticZipOutputStreamgetZipStreamEncode(OutputStreamoutput, Stringencode){ ZipOutputStreamzipStream=newZipOutputStream(output); if(encode==null||"".equals(encode)){ zipStream.setEncoding(DEFAULT_COMPRESS_ENCODE); }else{ zipStream.setEncoding(encode); } returnzipStream; } /** *访问本地路径下的所有文件 * *@parampath *@return */ publicstaticList<File>loadFiles(Stringpath){ List<File>list=null; try{ Filefold=newFile(path); if(fold.isDirectory()){ File[]files=fold.listFiles(); list=Arrays.asList(files); } }catch(Exceptione){ e.printStackTrace(); } returnlist; } /** *读取本地系统路径下的所有图片打成ZIP * *@parampath *@paramoutput *@paramcompress */ publicstaticvoidcompressZip(Stringpath,OutputStreamoutput, Stringencode,booleancompress){ List<File>listfiles=null; ZipOutputStreamzipStream=null; try{ zipStream=getZipStreamEncode(output,encode); listfiles=loadFiles(path); for(Filefile:listfiles){ compressZip(file,zipStream,compress); } }catch(Exceptione){ e.printStackTrace(); }finally{ try{ if(zipStream!=null){ zipStream.close(); } }catch(IOExceptione){ e.printStackTrace(); } } } /** *读取网络图片打成打成ZIP *@paramurls *key=图片名,value=图片URL *@paramoutput *@paramencode编码 *@paramcompress是否压缩 */ publicstaticvoidcompressZip(Map<String,String>urls, OutputStreamoutput,Stringencode,booleancompress){ ZipOutputStreamzipStream=null; try{ zipStream=getZipStreamEncode(output,encode); Map<String,String>synUrls=Collections.synchronizedMap(urls); Set<Entry<String,String>>set=synUrls.entrySet(); Iterator<Entry<String,String>>it=set.iterator(); while(it.hasNext()){ Entry<String,String>entry=it.next(); compressZip(entry.getValue(),zipStream,entry.getKey(), compress); } }catch(Exceptione){ e.printStackTrace(); }finally{ try{ if(zipStream!=null){ zipStream.close(); } }catch(IOExceptione){ e.printStackTrace(); } } } /** *压缩单个文件为ZIP *@paramfile *@paramoutput *@paramencode *@paramcompress */ publicstaticvoidcompressZip(Filefile,OutputStreamoutput, Stringencode,booleancompress)throwsException{ FileInputStreaminput=null; try{ input=newFileInputStream(file); compressZip(input,file.getName(),output,encode,compress); }catch(Exceptione){ e.printStackTrace(); }finally{ try{ if(input!=null) input.close(); }catch(IOExceptione){ e.printStackTrace(); } } } /** *压缩单个文件为ZIP *@paraminput *@paramfileName *@paramoutput *@paramencode *@paramcompress */ publicstaticvoidcompressZip(InputStreaminput,StringfileName, OutputStreamoutput,Stringencode,booleancompress)throwsException{ ZipOutputStreamzipStream=null; try{ zipStream=getZipStreamEncode(output,encode); zip(input,zipStream,fileName,compress); }catch(Exceptione){ e.printStackTrace(); }finally{ try{ if(zipStream!=null) zipStream.close(); }catch(IOExceptione){ e.printStackTrace(); } } } /** *本地图片 */ privatestaticvoidcompressZip(Filefile,ZipOutputStreamzipStream, booleancompress)throwsException{ FileInputStreaminput=null; try{ input=newFileInputStream(file); zip(input,zipStream,file.getName(),compress); }catch(Exceptione){ e.printStackTrace(); }finally{ try{ if(input!=null) input.close(); }catch(IOExceptione){ e.printStackTrace(); } } } /** *网络图片 * *@paramurl *@paramzipStream *@paramcompress */ privatestaticvoidcompressZip(Stringurl,ZipOutputStreamzipStream, StringfileName,booleancompress)throwsException{ InputStreaminput=null; try{ input=HttpHelpers.getInputStream(url); zip(input,zipStream,fileName,compress); }catch(Exceptione){ e.printStackTrace(); }finally{ try{ if(input!=null) input.close(); }catch(IOExceptione){ e.printStackTrace(); } } } /** *@paraminput *@paramzipStream *@paramzipEntryName *@paramcompress */ privatestaticvoidzip(InputStreaminput,ZipOutputStreamzipStream, StringzipEntryName,booleancompress)throwsException{ byte[]bytes=null; BufferedInputStreambufferStream=null; try{ if(input==null) thrownewException("获取压缩的数据项失败!数据项名为:"+zipEntryName); //压缩条目不是具体独立的文件,而是压缩包文件列表中的列表项,称为条目,就像索引一样 ZipEntryzipEntry=newZipEntry(zipEntryName); //定位到该压缩条目位置,开始写入文件到压缩包中 zipStream.putNextEntry(zipEntry); if(compress){ bytes=CompressPictureTools.compressOfQuality(input,0); zipStream.write(bytes,0,bytes.length); }else{ bytes=newbyte[1024*5];//读写缓冲区 bufferStream=newBufferedInputStream(input);//输入缓冲流 intread=0; while((read=bufferStream.read(bytes))!=-1){ zipStream.write(bytes,0,read); } } }catch(IOExceptione){ e.printStackTrace(); }finally{ try{ if(null!=bufferStream) bufferStream.close(); }catch(IOExceptione){ e.printStackTrace(); } } } }
以上就是Java 压缩图片并打成ZIP文件的示例的详细内容,更多关于Java 压缩图片打包成zip的资料请关注易盾网络其它相关文章!
本文共计1905个文字,预计阅读时间需要8分钟。
Java 获取网络或本地图片,压缩后打包成 ZIP,但获取网络流存在问题的解决方案:每次获取图片流的大小不一致(图片不完整),导致无法构建完整的图片进行压缩。以下是一种可能的解决方案代码:
javaimport java.io.*;import java.net.URL;import java.util.zip.ZipEntry;import java.util.zip.ZipOutputStream;
public class ImageCompressor { public static void main(String[] args) { String zipFile=output.zip; String[] imageUrls={ http://example.com/image1.jpg, http://example.com/image2.jpg // 更多图片 URL };
try (ZipOutputStream zos=new ZipOutputStream(new FileOutputStream(zipFile))) { for (String imageUrl : imageUrls) { byte[] imageBytes=getImageBytes(imageUrl); if (imageBytes !=null) { ZipEntry entry=new ZipEntry(imageUrl.substring(imageUrl.lastIndexOf(/) + 1)); zos.putNextEntry(entry); zos.write(imageBytes); zos.closeEntry(); } } } catch (IOException e) { e.printStackTrace(); } }
private static byte[] getImageBytes(String imageUrl) throws IOException { URL url=new URL(imageUrl); try (InputStream is=url.openStream()) { ByteArrayOutputStream buffer=new ByteArrayOutputStream(); int nRead; byte[] data=new byte[16384];
while ((nRead=is.read(data, 0, data.length)) !=-1) { buffer.write(data, 0, nRead); } buffer.flush(); return buffer.toByteArray(); } }}
这段代码首先定义了一个 `ImageCompressor` 类,其中包含一个 `main` 方法用于启动压缩过程。`getImageBytes` 方法用于从给定的 URL 获取图片的字节流。在 `main` 方法中,我们遍历图片 URL 数组,获取每个图片的字节流,并将其写入 ZIP 文件中。注意,这里假设每次获取的图片流是完整的,如果图片不完整,则需要进一步处理以确保获取到完整的图片数据。
JAVA 获取网络图片或本地图片压缩后打成ZIP,但是获取网络流存在问题:每次获取图片流的大小不一样(图片不完整),以致无法构建图片进行压缩?
/* 释以下代码:即可获取完整图片流网络不稳定情况且网络流是顺序读取,所以获得前部份流,不需要关闭连接,只需要将用完的流关闭即可 */ finally{ if(img.558idc.com/uploadfile/allimg/java/t.jpg"); byte[]buffer=newbyte[1024]; intcount=0; while((count=input.read(buffer))!=-1){ fout.write(buffer,0,count); } fout.flush(); }catch(Exceptione){ e.printStackTrace(); }finally{ try{ if(input!=null)input.close(); if(fout!=null)fout.close(); }catch(IOExceptione){ e.printStackTrace(); } } //2是否可以构建图片 try{ input=getInputStream("img.558idc.com/uploadfile/allimg/java/t.jpg"); ImageInputStreamiis=ImageIO.createImageInputStream(input); if(iis!=null){ Iterator<ImageReader>it=ImageIO.getImageReaders(iis); if(!it.hasNext()){ System.out.println("流不完整或不是图片!"); }else{ System.out.println(it.next().getFormatName()); } } }catch(Exceptione){ e.printStackTrace(); } } }
图片压缩采用thumbnailator,可以按大小、按比例、按质量压缩并增加水印,API简单
packagecom.sunshine.monitor.comm.util.compress; importjava.io.ByteArrayInputStream; importjava.io.ByteArrayOutputStream; importjava.io.File; importjava.io.FileInputStream; importjava.io.IOException; importjava.io.InputStream; importjavax.imageio.ImageIO; importnet.coobird.thumbnailator.Thumbnails; importnet.coobird.thumbnailator.geometry.Positions; /** *图片压缩:按大小、按比例压缩、按质量 *增加水印 *@authorOY * */ publicabstractclassCompressPictureTools{ privatestaticfloatQUALITY=0.6f; /** *按大小缩小 * *@paramfile *@paramwidth *@paramheight *@return *@throwsException */ publicstaticbyte[]compressOfSize(Filefile,intwidth,intheight) throwsException{ byte[]bs=null; InputStreaminput=null; try{ input=newFileInputStream(file); bs=compressOfSize(input,width,height); }catch(Exceptione){ e.printStackTrace(); }finally{ try{ if(input!=null) input.close(); }catch(IOExceptione){ e.printStackTrace(); } } returnbs; } /** *按大小缩小 * *@paraminput原图 *@paramwidth目标宽席 *@paramheight目标高度 *@return *@throwsException */ publicstaticbyte[]compressOfSize(InputStreaminput,intwidth,intheight) throwsException{ ByteArrayOutputStreamoutput=null; try{ output=newByteArrayOutputStream(); Thumbnails.of(input).size(width,height).toOutputStream(output); returnoutput.toByteArray(); }catch(IOExceptione){ e.printStackTrace(); }finally{ try{ if(output!=null) output.close(); }catch(IOExceptione){ e.printStackTrace(); } } returnnull; } /** *按指定比例进行缩小和放大:percent=1不变percent>1放大percent<1缩小 * *@paraminput原图 *@parampercent压缩比例 *@return *@throwsException */ publicstaticbyte[]compressOfPercent(InputStreaminput,floatpercent) throwsException{ ByteArrayOutputStreamoutput=null; try{ output=newByteArrayOutputStream(); Thumbnails.of(input).scale(percent).toOutputStream(output); returnoutput.toByteArray(); }catch(Exceptione){ e.printStackTrace(); }finally{ try{ if(output!=null) output.close(); }catch(IOExceptione){ e.printStackTrace(); } } returnnull; } /** *按指定比例进行缩小和放大:percent=1不变percent>1放大percent<1缩小 * *@paramfile原图 *@parampercent压缩比例 */ publicstaticbyte[]compressOfPercent(Filefile,floatpercent) throwsException{ byte[]bs=null; InputStreaminput=null; try{ input=newFileInputStream(file); bs=compressOfPercent(input,percent); }catch(Exceptione){ e.printStackTrace(); }finally{ try{ if(input!=null) input.close(); }catch(IOExceptione){ e.printStackTrace(); } } returnbs; } /** *按质量压缩:图片尺寸不变,压缩图片文件大小 * *@paramfile原图 *@paramquality *=1为最高质量 *@return *@throwsException */ publicstaticbyte[]compressOfQuality(Filefile,floatquality) throwsException{ byte[]bs=null; InputStreaminput=null; try{ input=newFileInputStream(file); bs=compressOfQuality(input,quality); }catch(Exceptione){ e.printStackTrace(); }finally{ try{ if(input!=null) input.close(); }catch(IOExceptione){ e.printStackTrace(); } } returnbs; } /** *按质量压缩:图片尺寸不变,压缩图片文件大小 * *@paraminput原图 *@paramquality *=1为最高质量 *@return *@throwsException */ publicstaticbyte[]compressOfQuality(InputStreaminput,floatquality) throwsException{ ByteArrayOutputStreamoutput=null; try{ output=newByteArrayOutputStream(); if(quality==0){ Thumbnails.of(input).scale(1f).outputQuality(QUALITY) .toOutputStream(output); }else{ Thumbnails.of(input).scale(1f).outputQuality(quality) .toOutputStream(output); } returnoutput.toByteArray(); }catch(Exceptione){ e.printStackTrace(); }finally{ try{ if(output!=null) output.close(); }catch(IOExceptione){ e.printStackTrace(); } } returnnull; } /** *图片右下角添加水印 * *@paramfromPic *原图 *@parammarkPic *水印图 *@paramtransparent *透明度 *@return *@throwsException */ publicstaticbyte[]waterMark(byte[]fromPic,InputStreammarkPic, floattransparent)throwsException{ InputStreamfinput=null; ByteArrayOutputStreamoutput=null; try{ finput=newByteArrayInputStream(fromPic); output=newByteArrayOutputStream(); Thumbnails .of(finput) .scale(1f) .watermark(Positions.BOTTOM_RIGHT,ImageIO.read(markPic), transparent).toOutputStream(output); returnoutput.toByteArray(); }catch(Exceptione){ e.printStackTrace(); }finally{ try{ if(output!=null) output.close(); if(finput!=null) finput.close(); }catch(IOExceptione){ e.printStackTrace(); } } returnnull; } /** *图片格式转换 * *@paramfromPic *原图 *@parampicFormat *格式png,jpg... *@return *@throwsException */ publicstaticbyte[]transferPicFormat(byte[]fromPic,StringpicFormat) throwsException{ ByteArrayInputStreamfinput=null; ByteArrayOutputStreamoutput=null; try{ finput=newByteArrayInputStream(fromPic); output=newByteArrayOutputStream(); Thumbnails.of(finput).outputFormat(picFormat) .toOutputStream(output); returnoutput.toByteArray(); }catch(Exceptione){ e.printStackTrace(); }finally{ try{ if(output!=null) output.close(); if(finput!=null) finput.close(); }catch(IOExceptione){ e.printStackTrace(); } } returnnull; } }
因JDK1.7以下,不可以设置编码,以致中文乱码问题,未采用java.util.ZipOutputStream,而是Apache ant下的ZipOutputStream
packagecom.sunshine.monitor.comm.util.compress; importjava.io.BufferedInputStream; importjava.io.File; importjava.io.FileInputStream; importjava.io.IOException; importjava.io.InputStream; importjava.io.OutputStream; importjava.util.Arrays; importjava.util.Collections; importjava.util.Iterator; importjava.util.List; importjava.util.Map; importjava.util.Map.Entry; importjava.util.Set; importorg.apache.tools.zip.ZipEntry; importorg.apache.tools.zip.ZipOutputStream; importcom.sunshine.monitor.comm.util.http.HttpHelpers; /** *图片压缩成ZIP,支持并发多线程; *java.util.ZipOutputStream中文乱码 *方法一、JDK1.7可以设置编码 *方法二、换成Apacheant *@authorOY * */ publicclassPicturePackZipTools{ privatestaticStringDEFAULT_COMPRESS_ENCODE="GBK"; privatestaticZipOutputStreamgetZipStreamEncode(OutputStreamoutput, Stringencode){ ZipOutputStreamzipStream=newZipOutputStream(output); if(encode==null||"".equals(encode)){ zipStream.setEncoding(DEFAULT_COMPRESS_ENCODE); }else{ zipStream.setEncoding(encode); } returnzipStream; } /** *访问本地路径下的所有文件 * *@parampath *@return */ publicstaticList<File>loadFiles(Stringpath){ List<File>list=null; try{ Filefold=newFile(path); if(fold.isDirectory()){ File[]files=fold.listFiles(); list=Arrays.asList(files); } }catch(Exceptione){ e.printStackTrace(); } returnlist; } /** *读取本地系统路径下的所有图片打成ZIP * *@parampath *@paramoutput *@paramcompress */ publicstaticvoidcompressZip(Stringpath,OutputStreamoutput, Stringencode,booleancompress){ List<File>listfiles=null; ZipOutputStreamzipStream=null; try{ zipStream=getZipStreamEncode(output,encode); listfiles=loadFiles(path); for(Filefile:listfiles){ compressZip(file,zipStream,compress); } }catch(Exceptione){ e.printStackTrace(); }finally{ try{ if(zipStream!=null){ zipStream.close(); } }catch(IOExceptione){ e.printStackTrace(); } } } /** *读取网络图片打成打成ZIP *@paramurls *key=图片名,value=图片URL *@paramoutput *@paramencode编码 *@paramcompress是否压缩 */ publicstaticvoidcompressZip(Map<String,String>urls, OutputStreamoutput,Stringencode,booleancompress){ ZipOutputStreamzipStream=null; try{ zipStream=getZipStreamEncode(output,encode); Map<String,String>synUrls=Collections.synchronizedMap(urls); Set<Entry<String,String>>set=synUrls.entrySet(); Iterator<Entry<String,String>>it=set.iterator(); while(it.hasNext()){ Entry<String,String>entry=it.next(); compressZip(entry.getValue(),zipStream,entry.getKey(), compress); } }catch(Exceptione){ e.printStackTrace(); }finally{ try{ if(zipStream!=null){ zipStream.close(); } }catch(IOExceptione){ e.printStackTrace(); } } } /** *压缩单个文件为ZIP *@paramfile *@paramoutput *@paramencode *@paramcompress */ publicstaticvoidcompressZip(Filefile,OutputStreamoutput, Stringencode,booleancompress)throwsException{ FileInputStreaminput=null; try{ input=newFileInputStream(file); compressZip(input,file.getName(),output,encode,compress); }catch(Exceptione){ e.printStackTrace(); }finally{ try{ if(input!=null) input.close(); }catch(IOExceptione){ e.printStackTrace(); } } } /** *压缩单个文件为ZIP *@paraminput *@paramfileName *@paramoutput *@paramencode *@paramcompress */ publicstaticvoidcompressZip(InputStreaminput,StringfileName, OutputStreamoutput,Stringencode,booleancompress)throwsException{ ZipOutputStreamzipStream=null; try{ zipStream=getZipStreamEncode(output,encode); zip(input,zipStream,fileName,compress); }catch(Exceptione){ e.printStackTrace(); }finally{ try{ if(zipStream!=null) zipStream.close(); }catch(IOExceptione){ e.printStackTrace(); } } } /** *本地图片 */ privatestaticvoidcompressZip(Filefile,ZipOutputStreamzipStream, booleancompress)throwsException{ FileInputStreaminput=null; try{ input=newFileInputStream(file); zip(input,zipStream,file.getName(),compress); }catch(Exceptione){ e.printStackTrace(); }finally{ try{ if(input!=null) input.close(); }catch(IOExceptione){ e.printStackTrace(); } } } /** *网络图片 * *@paramurl *@paramzipStream *@paramcompress */ privatestaticvoidcompressZip(Stringurl,ZipOutputStreamzipStream, StringfileName,booleancompress)throwsException{ InputStreaminput=null; try{ input=HttpHelpers.getInputStream(url); zip(input,zipStream,fileName,compress); }catch(Exceptione){ e.printStackTrace(); }finally{ try{ if(input!=null) input.close(); }catch(IOExceptione){ e.printStackTrace(); } } } /** *@paraminput *@paramzipStream *@paramzipEntryName *@paramcompress */ privatestaticvoidzip(InputStreaminput,ZipOutputStreamzipStream, StringzipEntryName,booleancompress)throwsException{ byte[]bytes=null; BufferedInputStreambufferStream=null; try{ if(input==null) thrownewException("获取压缩的数据项失败!数据项名为:"+zipEntryName); //压缩条目不是具体独立的文件,而是压缩包文件列表中的列表项,称为条目,就像索引一样 ZipEntryzipEntry=newZipEntry(zipEntryName); //定位到该压缩条目位置,开始写入文件到压缩包中 zipStream.putNextEntry(zipEntry); if(compress){ bytes=CompressPictureTools.compressOfQuality(input,0); zipStream.write(bytes,0,bytes.length); }else{ bytes=newbyte[1024*5];//读写缓冲区 bufferStream=newBufferedInputStream(input);//输入缓冲流 intread=0; while((read=bufferStream.read(bytes))!=-1){ zipStream.write(bytes,0,read); } } }catch(IOExceptione){ e.printStackTrace(); }finally{ try{ if(null!=bufferStream) bufferStream.close(); }catch(IOExceptione){ e.printStackTrace(); } } } }
以上就是Java 压缩图片并打成ZIP文件的示例的详细内容,更多关于Java 压缩图片打包成zip的资料请关注易盾网络其它相关文章!

