001/******************************************************************************* 002 * This software is provided as a supplement to the authors' textbooks on digital 003 * image processing published by Springer-Verlag in various languages and editions. 004 * Permission to use and distribute this software is granted under the BSD 2-Clause 005 * "Simplified" License (see http://opensource.org/licenses/BSD-2-Clause). 006 * Copyright (c) 2006-2023 Wilhelm Burger, Mark J. Burge. All rights reserved. 007 * Visit https://imagingbook.com for additional details. 008 ******************************************************************************/ 009package imagingbook.common.util; 010 011import java.io.ByteArrayOutputStream; 012import java.io.IOException; 013import java.util.zip.DataFormatException; 014import java.util.zip.Deflater; 015import java.util.zip.Inflater; 016 017/** 018 * This class provides ZIP-compression/decompression of byte arrays. 019 * 020 * @author WB 021 * @version 2022/09/06 022 */ 023public class ZipCompressor { 024 025 private final boolean nowrap; // true -> ZLIB header and checksum fields will not be used 026 private final int bufsize; 027 028 public ZipCompressor(int bufsize, boolean nowrap) { 029 this.bufsize = bufsize; 030 this.nowrap = nowrap; 031 } 032 033 public ZipCompressor() { 034 this(1024, true); 035 } 036 037 // ----------------------------------------------------------- 038 039 public byte[] compressByteArray(byte[] inputBytes){ 040 Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION, nowrap); 041 deflater.setInput(inputBytes); 042 deflater.finish(); 043 044 final byte[] buf = new byte[bufsize]; 045 byte[] outputBytes = null; 046 047 try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { 048 while (!deflater.finished()) { 049 int size = deflater.deflate(buf); 050 bos.write(buf, 0, size); 051 } 052 outputBytes = bos.toByteArray(); 053 } catch (IOException e) { } 054 055 return outputBytes; 056 } 057 058 public byte[] decompressByteArray(byte[] inputBytes){ 059 Inflater inflater = new Inflater(nowrap); 060 inflater.setInput(inputBytes); 061 062 final byte[] buf = new byte[bufsize]; 063 byte[] outputBytes = null; 064 065 try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { 066 while(!inflater.finished()){ 067 int size = inflater.inflate(buf); 068 bos.write(buf, 0, size); 069 } 070 outputBytes = bos.toByteArray(); 071 } catch (IOException | DataFormatException e) { } 072 073 return outputBytes; 074 } 075 076}