Creates a new deflate stream for compression. If a given argument is nil, the default value of that argument is used.
The level sets the compression level for the deflate stream
between 0 (no compression) and 9 (best compression. The following constants
have been defined to make code more readable:
-
Zlib::NO_COMPRESSION = 0
-
Zlib::BEST_SPEED = 1
-
Zlib::DEFAULT_COMPRESSION = 6
-
Zlib::BEST_COMPRESSION = 9
The window_bits sets the size of the history buffer and should
be between 8 and 15. Larger values of this parameter result in better
compression at the expense of memory usage.
The mem_level specifies how much memory should be allocated
for the internal compression state. 1 uses minimum memory but is slow and
reduces compression ratio while 9 uses maximum memory for optimal speed.
The default value is 8. Two constants are defined:
-
Zlib::DEF_MEM_LEVEL
-
Zlib::MAX_MEM_LEVEL
The strategy sets the deflate compression strategy. The
following strategies are available:
- Zlib::DEFAULT_STRATEGY
-
For normal data
- Zlib::FILTERED
-
For data produced by a filter or predictor
- Zlib::FIXED
-
Prevents dynamic Huffman codes
- Zlib::HUFFMAN_ONLY
-
Prevents string matching
- Zlib::RLE
-
Designed for better compression of PNG image data
See the constants for further description.
Examples
Basic
open "compressed.file", "w+" do |io|
io << Zlib::Deflate.new.deflate(File.read("big.file"))
end
Custom compression
open "compressed.file", "w+" do |compressed_io|
deflate = Zlib::Deflate.new(Zlib::BEST_COMPRESSION,
Zlib::MAX_WBITS,
Zlib::MAX_MEM_LEVEL,
Zlib::HUFFMAN_ONLY)
begin
open "big.file" do |big_io|
until big_io.eof? do
compressed_io << zd.deflate(big_io.read(16384))
end
end
ensure
deflate.close
end
end
While this example will work, for best optimization review the flags for your specific time, memory usage and output space requirements.
Please login to continue.