您好,登錄后才能下訂單哦!
這期內(nèi)容當中小編將會給大家?guī)碛嘘P利用Java怎么將圖片進行壓縮并打包成ZIP文件,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
JAVA 獲取網(wǎng)絡圖片或本地圖片壓縮后打成ZIP,但是獲取網(wǎng)絡流存在問題:每次獲取圖片流的大小不一樣(圖片不完整),以致無法構(gòu)建圖片進行壓縮?
/* 釋以下代碼:即可獲取完整圖片流網(wǎng)絡不穩(wěn)定情況且網(wǎng)絡流是順序讀取,所以獲得前部份流,不需要關閉連接,只需要將用完的流關閉即可 */ 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)絡圖片 * * @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圖片本地存儲大小 OutputStream fout = null; InputStream input = null; try { fout = new FileOutputStream("F:" + File.separator + "1.jpg"); input = getInputStream("https://cache.yisu.com/upload/information/20201203/112/1.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("https://cache.yisu.com/upload/information/20201203/112/1.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簡單
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 目標寬席 * @param height 目標高度 * @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; } /** * 按指定比例進行縮小和放大: 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; } /** * 按指定比例進行縮小和放大: 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以下,不可以設置編碼,以致中文亂碼問題,未采用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可以設置編碼 * 方法二、換成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)絡圖片打成打成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(); } } } /** * 壓縮單個文件為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(); } } } /** * 壓縮單個文件為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)絡圖片 * * @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ù)項失敗! 數(shù)據(jù)項名為:" + zipEntryName); // 壓縮條目不是具體獨立的文件,而是壓縮包文件列表中的列表項,稱為條目,就像索引一樣 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文件了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業(yè)資訊頻道。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。