Java 壓縮圖片并打包成ZIP文件的示例
JAVA 獲取網(wǎng)絡(luò)圖片或本地圖片壓縮后打成ZIP,但是獲取網(wǎng)絡(luò)流存在問題:每次獲取圖片流的大小不一樣(圖片不完整),以致無(wú)法構(gòu)建圖片進(jìn)行壓縮?
/* 釋以下代碼:即可獲取完整圖片流網(wǎng)絡(luò)不穩(wěn)定情況且網(wǎng)絡(luò)流是順序讀取,所以獲得前部份流,不需要關(guān)閉連接,只需要將用完的流關(guān)閉即可 */ finally{ if(httpCon != null) httpCon.disconnect(); }
package com.sunshine.monitor.comm.util.http; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.Iterator; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; import sun.net.www.protocol.ftp.FtpURLConnection; /** * 獲取網(wǎng)絡(luò)圖片 * * @author OY */ public abstract class HttpHelpers {private static final String KEY = 'file.encoding';private static final String ENCODING = 'GBK';public static InputStream getInputStream(String url) throws Exception{ URLConnection con = null; HttpURLConnection httpCon = null; FtpURLConnection ftpCon= null; try { System.setProperty(KEY, ENCODING); URL _url = new URL(url); con = _url.openConnection(); con.setConnectTimeout(3000); con.setUseCaches(false);// 不緩存 con.setDefaultUseCaches(false); if (con instanceof HttpURLConnection) { httpCon = (HttpURLConnection) con; httpCon.setInstanceFollowRedirects(true); //httpCon.setRequestProperty('Accept-Charset', 'utf-8'); if (httpCon.getResponseCode() >= 300) { System.out.println('URL:' + url + ',HTTP Request is not success, Response code is ' + httpCon.getResponseCode()); } else { return httpCon.getInputStream(); } } else if(con instanceof FtpURLConnection){ ftpCon = (FtpURLConnection)con; return ftpCon.getInputStream(); } } catch (Exception e) { e.printStackTrace(); }finally{ if(httpCon != null) httpCon.disconnect(); } return null; } public static void main(String[] args) { // 1圖片本地存儲(chǔ)大小 OutputStream fout = null; InputStream input = null; try { fout = new FileOutputStream('F:' + File.separator + '1.jpg'); input = getInputStream('http://192.168.1.200/t.jpg'); byte[] buffer = new byte[1024]; int count = 0 ; while((count=input.read(buffer)) != -1){ fout.write(buffer, 0, count); } fout.flush(); } catch (Exception e) { e.printStackTrace(); } finally{ try { if(input != null) input.close(); if(fout != null) fout.close(); } catch (IOException e) { e.printStackTrace(); } } // 2是否可以構(gòu)建圖片 try { input = getInputStream('http://192.168.1.200/t.jpg'); ImageInputStream iis = 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 (Exception e) { e.printStackTrace(); } } }
圖片壓縮采用thumbnailator,可以按大小、按比例、按質(zhì)量壓縮并增加水印,API簡(jiǎn)單
package com.sunshine.monitor.comm.util.compress; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import javax.imageio.ImageIO; import net.coobird.thumbnailator.Thumbnails; import net.coobird.thumbnailator.geometry.Positions; /** * 圖片壓縮:按大小、按比例壓縮、按質(zhì)量 * 增加水印 * @author OY * */ public abstract class CompressPictureTools {private static float QUALITY = 0.6f; /** * 按大小縮小 * * @param file * @param width * @param height * @return * @throws Exception */ public static byte[] compressOfSize(File file, int width, int height) throws Exception { byte[] bs = null; InputStream input = null; try { input = new FileInputStream(file); bs = compressOfSize(input, width, height); } catch (Exception e) { e.printStackTrace(); } finally { try { if (input != null) input.close(); } catch (IOException e) { e.printStackTrace(); } } return bs; }/** * 按大小縮小 * * @param input 原圖 * @param width 目標(biāo)寬席 * @param height 目標(biāo)高度 * @return * @throws Exception */ public static byte[] compressOfSize(InputStream input, int width, int height) throws Exception { ByteArrayOutputStream output = null; try { output = new ByteArrayOutputStream(); Thumbnails.of(input).size(width, height).toOutputStream(output); return output.toByteArray(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (output != null) output.close(); } catch (IOException e) { e.printStackTrace(); } } return null; }/** * 按指定比例進(jìn)行縮小和放大: percent=1不變 percent>1放大 percent<1縮小 * * @param input 原圖 * @param percent 壓縮比例 * @return * @throws Exception */ public static byte[] compressOfPercent(InputStream input, float percent) throws Exception { ByteArrayOutputStream output = null; try { output = new ByteArrayOutputStream(); Thumbnails.of(input).scale(percent).toOutputStream(output); return output.toByteArray(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (output != null) output.close(); } catch (IOException e) { e.printStackTrace(); } } return null; }/** * 按指定比例進(jìn)行縮小和放大: percent=1不變 percent>1放大 percent<1縮小 * * @param file 原圖 * @param percent 壓縮比例 */ public static byte[] compressOfPercent(File file, float percent) throws Exception { byte[] bs = null; InputStream input = null; try { input = new FileInputStream(file); bs = compressOfPercent(input, percent); } catch (Exception e) { e.printStackTrace(); } finally { try { if (input != null) input.close(); } catch (IOException e) { e.printStackTrace(); } } return bs; }/** * 按質(zhì)量壓縮:圖片尺寸不變,壓縮圖片文件大小 * * @param file 原圖 * @param quality * =1為最高質(zhì)量 * @return * @throws Exception */ public static byte[] compressOfQuality(File file, float quality) throws Exception { byte[] bs = null; InputStream input = null; try { input = new FileInputStream(file); bs = compressOfQuality(input, quality); } catch (Exception e) { e.printStackTrace(); } finally { try { if (input != null) input.close(); } catch (IOException e) { e.printStackTrace(); } } return bs; }/** * 按質(zhì)量壓縮:圖片尺寸不變,壓縮圖片文件大小 * * @param input 原圖 * @param quality * =1為最高質(zhì)量 * @return * @throws Exception */ public static byte[] compressOfQuality(InputStream input, float quality) throws Exception { ByteArrayOutputStream output = null; try { output = new ByteArrayOutputStream(); if(quality == 0){ Thumbnails.of(input).scale(1f).outputQuality(QUALITY) .toOutputStream(output); } else { Thumbnails.of(input).scale(1f).outputQuality(quality) .toOutputStream(output); } return output.toByteArray(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (output != null) output.close(); } catch (IOException e) { e.printStackTrace(); } } return null; }/** * 圖片右下角添加水印 * * @param fromPic * 原圖 * @param markPic * 水印圖 * @param transparent * 透明度 * @return * @throws Exception */ public static byte[] waterMark(byte[] fromPic, InputStream markPic, float transparent) throws Exception { InputStream finput = null; ByteArrayOutputStream output = null; try { finput = new ByteArrayInputStream(fromPic); output = new ByteArrayOutputStream(); Thumbnails .of(finput) .scale(1f) .watermark(Positions.BOTTOM_RIGHT, ImageIO.read(markPic), transparent).toOutputStream(output); return output.toByteArray(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (output != null) output.close(); if (finput != null) finput.close(); } catch (IOException e) { e.printStackTrace(); } } return null; }/** * 圖片格式轉(zhuǎn)換 * * @param fromPic * 原圖 * @param picFormat * 格式 png,jpg... * @return * @throws Exception */ public static byte[] transferPicFormat(byte[] fromPic, String picFormat) throws Exception { ByteArrayInputStream finput = null; ByteArrayOutputStream output = null; try { finput = new ByteArrayInputStream(fromPic); output = new ByteArrayOutputStream(); Thumbnails.of(finput).outputFormat(picFormat) .toOutputStream(output); return output.toByteArray(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (output != null) output.close(); if (finput != null) finput.close(); } catch (IOException e) { e.printStackTrace(); } } return null; } }
因JDK1.7以下,不可以設(shè)置編碼,以致中文亂碼問題,未采用java.util.ZipOutputStream,而是Apache ant下的ZipOutputStream
package com.sunshine.monitor.comm.util.compress; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipOutputStream; import com.sunshine.monitor.comm.util.http.HttpHelpers; /** * 圖片壓縮成ZIP,支持并發(fā)多線程; * java.util.ZipOutputStream中文亂碼 * 方法一、JDK1.7可以設(shè)置編碼 * 方法二、換成Apache ant * @author OY * */ public class PicturePackZipTools { private static String DEFAULT_COMPRESS_ENCODE = 'GBK'; private static ZipOutputStream getZipStreamEncode(OutputStream output, String encode) { ZipOutputStream zipStream = new ZipOutputStream(output); if (encode == null || ''.equals(encode)) { zipStream.setEncoding(DEFAULT_COMPRESS_ENCODE); } else { zipStream.setEncoding(encode); } return zipStream; }/** * 訪問本地路徑下的所有文件 * * @param path * @return */ public static List<File> loadFiles(String path) { List<File> list = null; try { File fold = new File(path); if (fold.isDirectory()) { File[] files = fold.listFiles(); list = Arrays.asList(files); } } catch (Exception e) { e.printStackTrace(); } return list; }/** * 讀取本地系統(tǒng)路徑下的所有圖片打成ZIP * * @param path * @param output * @param compress */ public static void compressZip(String path, OutputStream output, String encode, boolean compress) { List<File> listfiles = null; ZipOutputStream zipStream = null; try { zipStream = getZipStreamEncode(output, encode); listfiles = loadFiles(path); for (File file : listfiles) { compressZip(file, zipStream, compress); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (zipStream != null) { zipStream.close(); } } catch (IOException e) { e.printStackTrace(); } } }/** * 讀取網(wǎng)絡(luò)圖片打成打成ZIP * @param urls * key = 圖片名, value = 圖片URL * @param output * @param encode 編碼 * @param compress 是否壓縮 */ public static void compressZip(Map<String, String> urls, OutputStream output, String encode, boolean compress) { ZipOutputStream zipStream = 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 (Exception e) { e.printStackTrace(); } finally { try { if (zipStream != null) { zipStream.close(); } } catch (IOException e) { e.printStackTrace(); } } }/** * 壓縮單個(gè)文件為ZIP * @param file * @param output * @param encode * @param compress */ public static void compressZip(File file, OutputStream output, String encode, boolean compress) throws Exception{ FileInputStream input = null; try { input = new FileInputStream(file); compressZip(input,file.getName(),output,encode,compress); } catch (Exception e) { e.printStackTrace(); } finally { try { if (input != null) input.close(); } catch (IOException e) { e.printStackTrace(); } }}/** * 壓縮單個(gè)文件為ZIP * @param input * @param fileName * @param output * @param encode * @param compress */ public static void compressZip(InputStream input, String fileName, OutputStream output, String encode, boolean compress) throws Exception { ZipOutputStream zipStream = null; try { zipStream = getZipStreamEncode(output, encode); zip(input, zipStream, fileName, compress); } catch (Exception e) { e.printStackTrace(); } finally { try { if (zipStream != null) zipStream.close(); } catch (IOException e) { e.printStackTrace(); } } }/** * 本地圖片 */ private static void compressZip(File file, ZipOutputStream zipStream, boolean compress) throws Exception{ FileInputStream input = null; try { input = new FileInputStream(file); zip(input, zipStream, file.getName(), compress); } catch (Exception e) { e.printStackTrace(); }finally{ try { if(input != null) input.close(); } catch (IOException e) { e.printStackTrace(); } } }/** * 網(wǎng)絡(luò)圖片 * * @param url * @param zipStream * @param compress */ private static void compressZip(String url, ZipOutputStream zipStream, String fileName, boolean compress) throws Exception{ InputStream input = null; try { input = HttpHelpers.getInputStream(url); zip(input, zipStream, fileName, compress); } catch (Exception e) { e.printStackTrace(); } finally{ try { if(input != null) input.close(); } catch (IOException e) { e.printStackTrace(); } } }/** * @param input * @param zipStream * @param zipEntryName * @param compress */ private static void zip(InputStream input, ZipOutputStream zipStream, String zipEntryName, boolean compress) throws Exception{ byte[] bytes = null; BufferedInputStream bufferStream = null; try { if(input == null) throw new Exception('獲取壓縮的數(shù)據(jù)項(xiàng)失敗! 數(shù)據(jù)項(xiàng)名為:' + zipEntryName); // 壓縮條目不是具體獨(dú)立的文件,而是壓縮包文件列表中的列表項(xiàng),稱為條目,就像索引一樣 ZipEntry zipEntry = new ZipEntry(zipEntryName); // 定位到該壓縮條目位置,開始寫入文件到壓縮包中 zipStream.putNextEntry(zipEntry); if (compress) { bytes = CompressPictureTools.compressOfQuality(input, 0); zipStream.write(bytes, 0, bytes.length); } else { bytes = new byte[1024 * 5];// 讀寫緩沖區(qū) bufferStream = new BufferedInputStream(input);// 輸入緩沖流 int read = 0; while ((read = bufferStream.read(bytes)) != -1) { zipStream.write(bytes, 0, read); } } } catch (IOException e) { e.printStackTrace(); } finally { try { if (null != bufferStream) bufferStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }
以上就是Java 壓縮圖片并打成ZIP文件的示例的詳細(xì)內(nèi)容,更多關(guān)于Java 壓縮圖片打包成zip的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. python公司內(nèi)項(xiàng)目對(duì)接釘釘審批流程的實(shí)現(xiàn)2. Python操作Excel工作簿的示例代碼(*.xlsx)3. Python TKinter如何自動(dòng)關(guān)閉主窗口4. Python 利用flask搭建一個(gè)共享服務(wù)器的步驟5. Python importlib模塊重載使用方法詳解6. python用zip壓縮與解壓縮7. Python中Anaconda3 安裝gdal庫(kù)的方法8. Python 簡(jiǎn)介9. Python自動(dòng)化之定位方法大殺器xpath10. Python本地及虛擬解釋器配置過程解析
