### Compression Results Output
Source: https://github.com/depsypher/pngtastic/blob/master/README.md
Example output logs showing compression statistics for default, ImageOptim, and Zopfli methods.
```text
Pngtastic Default Compression
[pngtastic] 59.76% : 169B -> 68B ( 101B saved) - build/images/optimizer/1px.png
[pngtastic] 5.99% : 35731B -> 33590B ( 2141B saved) - build/images/optimizer/amigaball.png
[pngtastic] 0.01% :251938B ->251922B ( 16B saved) - build/images/optimizer/frymire.png
[pngtastic] 22.37% : 93167B -> 72322B (20845B saved) - build/images/optimizer/gamma.png
ImageOptim Compression
[ImageOptim] 59.8% : 169B -> 73B - build/images/optimizer/1px.png
[ImageOptim] 11.2% : 35731B -> 31729B - build/images/optimizer/amigaball.png
[ImageOptim] 8.7% :251938B ->230055B - build/images/optimizer/frymire.png
[ImageOptim] 28.5% : 93167B -> 66607B - build/images/optimizer/gamma.png
Pngtastic Zopfli Compression
[pngtastic] 61.54% : 169B -> 65B ( 104B saved) - build/images/optimizer/1px.png
[pngtastic] 12.21% : 35731B -> 31370B ( 4361B saved) - build/images/optimizer/amigaball.png
[pngtastic] 10.40% :251938B ->225749B (26189B saved) - build/images/optimizer/frymire.png
[pngtastic] 29.27% : 93167B -> 65895B (27272B saved) - build/images/optimizer/gamma.png
```
--------------------------------
### Optimize PNG Image in Java
Source: https://github.com/depsypher/pngtastic/wiki/Calling-pngtastic-from-java
Demonstrates loading a PNG file, running the optimizer, and saving the result to a new file path.
```java
package example;
import com.googlecode.pngtastic.core.PngImage;
import com.googlecode.pngtastic.core.PngOptimizer;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
/**
* Example pngtastic image optimization usage from java
*/
public class Test {
public static void main(String[] args) throws Exception {
// load png image from a file
final InputStream in = new BufferedInputStream(new FileInputStream("/input.png"));
final PngImage image = new PngImage(in);
// optimize
final PngOptimizer optimizer = new PngOptimizer();
final PngImage optimizedImage = optimizer.optimize(image);
// export the optimized image to a new file
final ByteArrayOutputStream optimizedBytes = new ByteArrayOutputStream();
optimizedImage.writeDataOutputStream(optimizedBytes);
optimizedImage.export("/output.png", optimizedBytes.toByteArray());
}
}
```
--------------------------------
### Run Pngtastic Optimizer
Source: https://github.com/depsypher/pngtastic/blob/master/README.md
Execute the optimizer from the command line using the Zopfli compressor.
```bash
$ mvn install
$ java -cp target/pngtastic-1.8-SNAPSHOT.jar com.googlecode.pngtastic.PngtasticOptimizer --compressor zopfli --iterations 32 --fileSuffix .min.png images/optimizer/amigaball.png
```
--------------------------------
### Optimize PNG via Command Line
Source: https://context7.com/depsypher/pngtastic/llms.txt
Run the optimizer utility from the terminal to process PNG files.
```bash
# Build the project
mvn install
# Basic optimization
java -cp target/pngtastic-1.8-SNAPSHOT.jar \
com.googlecode.pngtastic.PngtasticOptimizer \
image.png
```
--------------------------------
### Maximum PNG Compression with Zopfli
Source: https://context7.com/depsypher/pngtastic/llms.txt
Employ Zopfli compressor for maximum file size reduction, specifying iterations for the compression process.
```bash
java -cp target/pngtastic-1.8-SNAPSHOT.jar \
com.googlecode.pngtastic.PngtasticOptimizer \
--compressor zopfli \
--iterations 32 \
--fileSuffix .min.png \
--toDir optimized \
images/amigaball.png
```
--------------------------------
### Optimize PNG Images with Options
Source: https://context7.com/depsypher/pngtastic/llms.txt
Use this command to optimize PNG files in a directory, specifying output directory, file suffix, gamma removal, and compression level.
```bash
java -cp target/pngtastic-1.8-SNAPSHOT.jar \
com.googlecode.pngtastic.PngtasticOptimizer \
--toDir output \
--fileSuffix .min.png \
--removeGamma true \
--compressionLevel 9 \
--logLevel info \
images/*.png
```
--------------------------------
### PngOptimizer Zopfli Compression
Source: https://context7.com/depsypher/pngtastic/llms.txt
Use Zopfli compression for superior compression ratios. Adjust iterations to balance compression speed and ratio. Requires setting the compressor and iteration count.
```java
import com.googlecode.pngtastic.core.PngImage;
import com.googlecode.pngtastic.core.PngOptimizer;
import java.io.ByteArrayOutputStream;
public class ZopfliCompressionExample {
public static void main(String[] args) throws Exception {
// Create optimizer
PngOptimizer optimizer = new PngOptimizer("info");
// Enable Zopfli compression with 32 iterations
// More iterations = better compression but slower
optimizer.setCompressor("zopfli", 32);
// Load and optimize
PngImage image = new PngImage("/path/to/input.png", "info");
PngImage optimized = optimizer.optimize(image, false, null);
// Export result
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
optimized.writeDataOutputStream(bytes);
optimized.export("/path/to/output-zopfli.png", bytes.toByteArray());
System.out.println("Bytes saved with Zopfli: " + optimizer.getTotalSavings());
}
}
```
--------------------------------
### Load PNG Image with Pngtastic
Source: https://context7.com/depsypher/pngtastic/llms.txt
Demonstrates loading a PNG image using Pngtastic's PngImage class from various sources like file paths, input streams, and byte arrays. Also shows how to access basic image properties.
```java
import com.googlecode.pngtastic.core.PngImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
public class LoadImageExample {
public static void main(String[] args) throws Exception {
// Load from file path with logging
PngImage imageFromFile = new PngImage("/path/to/image.png", "info");
// Load from InputStream
InputStream inputStream = new BufferedInputStream(new FileInputStream("/path/to/image.png"));
PngImage imageFromStream = new PngImage(inputStream);
// Load from byte array
byte[] imageBytes = java.nio.file.Files.readAllBytes(java.nio.file.Paths.get("/path/to/image.png"));
PngImage imageFromBytes = new PngImage(imageBytes);
// Access image properties
System.out.println("Width: " + imageFromFile.getWidth());
System.out.println("Height: " + imageFromFile.getHeight());
System.out.println("Bit Depth: " + imageFromFile.getBitDepth());
System.out.println("Color Type: " + imageFromFile.getColorType());
System.out.println("Interlace: " + imageFromFile.getInterlace());
}
}
```
--------------------------------
### Ant Task for Advanced PNG Optimization with Zopfli
Source: https://context7.com/depsypher/pngtastic/llms.txt
Configure the Pngtastic Ant task for advanced optimization using Zopfli, including file suffix, gamma removal, and specific compression settings.
```xml
```
--------------------------------
### Layer Multiple PNG Images
Source: https://context7.com/depsypher/pngtastic/llms.txt
Composite multiple PNG images from the command line to create layered images, specifying output directory and filename.
```bash
java -cp target/pngtastic-1.8-SNAPSHOT.jar \
com.googlecode.pngtastic.PngtasticLayerer \
--toDir output \
--outFile composited.png \
--compressionLevel 9 \
--logLevel info \
background.png foreground.png overlay.png
```
--------------------------------
### CLI PngtasticOptimizer
Source: https://context7.com/depsypher/pngtastic/llms.txt
Optimizes PNG images using standard or Zopfli compression.
```APIDOC
## CLI PngtasticOptimizer
### Description
Optimizes PNG images with support for gamma removal, compression levels, and Zopfli compression.
### Method
CLI Execution
### Parameters
#### Options
- **--toDir** (string) - Required - Output directory
- **--fileSuffix** (string) - Optional - Suffix for output files
- **--removeGamma** (boolean) - Optional - Remove gamma correction info
- **--compressionLevel** (integer) - Optional - Compression level 0-9
- **--compressor** (string) - Optional - Use "zopfli" for better compression
- **--iterations** (integer) - Optional - Zopfli iterations (default: 15)
- **--logLevel** (string) - Optional - Logging: none, debug, info, or error
```
--------------------------------
### Ant Task Integration
Source: https://context7.com/depsypher/pngtastic/llms.txt
Integrate Pngtastic into Ant build processes.
```APIDOC
## Ant Task Integration
### Description
Integrate Pngtastic into Ant build processes for automated PNG optimization during builds.
### Parameters
#### Attributes
- **toDir** (string) - Required - Output directory
- **fileSuffix** (string) - Optional - Suffix for output files
- **removeGamma** (boolean) - Optional - Remove gamma correction
- **compressionLevel** (integer) - Optional - Compression level 0-9
- **compressor** (string) - Optional - Use "zopfli" for better compression
- **iterations** (integer) - Optional - Zopfli iterations
- **generateDataUriCss** (boolean) - Optional - Generate CSS data URIs
- **logLevel** (string) - Optional - none, debug, info, or error
```
--------------------------------
### Basic PNG Image Optimization
Source: https://context7.com/depsypher/pngtastic/llms.txt
Optimizes a PNG image using Pngtastic's PngOptimizer to reduce file size. The optimized image is then exported to a new file, and the total bytes saved are reported.
```java
import com.googlecode.pngtastic.core.PngImage;
import com.googlecode.pngtastic.core.PngOptimizer;
import java.io.ByteArrayOutputStream;
public class BasicOptimizationExample {
public static void main(String[] args) throws Exception {
// Load the original image
PngImage image = new PngImage("/path/to/input.png", "info");
// Create optimizer instance
PngOptimizer optimizer = new PngOptimizer();
// Optimize the image (returns a new optimized PngImage)
PngImage optimizedImage = optimizer.optimize(image);
// Export to file
ByteArrayOutputStream optimizedBytes = new ByteArrayOutputStream();
optimizedImage.writeDataOutputStream(optimizedBytes);
optimizedImage.export("/path/to/output.png", optimizedBytes.toByteArray());
// Check savings
System.out.println("Total bytes saved: " + optimizer.getTotalSavings());
}
}
```
--------------------------------
### Ant Task for Basic PNG Optimization
Source: https://context7.com/depsypher/pngtastic/llms.txt
Define and use the Pngtastic Ant task for basic image optimization, specifying the output directory and log level.
```xml
```
--------------------------------
### PngOptimizer Class - Image Optimization
Source: https://context7.com/depsypher/pngtastic/llms.txt
The PngOptimizer class provides methods to reduce PNG file sizes through filtering and compression.
```APIDOC
## PngOptimizer Class
### Description
Optimizes PNG images by applying filtering strategies and compression techniques.
### Methods
- **optimize(PngImage image)**: Optimizes the provided PngImage and returns a new optimized instance.
- **optimize(PngImage image, String outputPath, boolean removeGamma, Integer compressionLevel)**: Optimizes image and saves directly to the specified path.
- **getTotalSavings()**: Returns the total number of bytes saved across optimization operations.
- **getResults()**: Returns a list of OptimizerResult objects containing detailed metrics for each optimization.
```
--------------------------------
### Composite Multiple PNG Layers
Source: https://context7.com/depsypher/pngtastic/llms.txt
Sequentially layer images onto a base image and optimize the final output.
```java
import com.googlecode.pngtastic.core.PngImage;
import com.googlecode.pngtastic.core.PngLayerer;
import com.googlecode.pngtastic.core.PngOptimizer;
import java.io.ByteArrayOutputStream;
public class MultipleLayersExample {
public static void main(String[] args) throws Exception {
PngLayerer layerer = new PngLayerer("info");
PngOptimizer optimizer = new PngOptimizer("info");
// Start with base layer
PngImage composite = new PngImage("/path/to/base.png", "info");
// Layer multiple images on top
String[] layers = {
"/path/to/body.png",
"/path/to/face.png",
"/path/to/eyes.png",
"/path/to/accessory.png"
};
for (String layerPath : layers) {
PngImage layer = new PngImage(layerPath, "info");
composite = layerer.layer(composite, layer, null, false);
}
// Export and optimize the final composite
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
composite.writeDataOutputStream(bytes);
composite.setFileName("/path/to/final.png");
composite.export("/path/to/final.png", bytes.toByteArray());
// Optimize the result
optimizer.optimize(composite, "/path/to/final-optimized.png", false, null);
}
}
```
--------------------------------
### PngOptimizer Data URI CSS Generation
Source: https://context7.com/depsypher/pngtastic/llms.txt
Generate CSS with Base64-encoded data URIs for direct image embedding in stylesheets. This reduces HTTP requests. Enable the feature and then generate the CSS file.
```java
import com.googlecode.pngtastic.core.PngImage;
import com.googlecode.pngtastic.core.PngOptimizer;
public class DataUriCssExample {
public static void main(String[] args) throws Exception {
PngOptimizer optimizer = new PngOptimizer("info");
// Enable data URI CSS generation
optimizer.setGenerateDataUriCss(true);
// Optimize multiple images
String[] files = {"icon1.png", "icon2.png", "icon3.png"};
for (String file : files) {
PngImage image = new PngImage(file, "info");
optimizer.optimize(image, "optimized/" + file, false, null);
}
// Generate HTML file with embedded CSS data URIs
optimizer.generateDataUriCss("output");
// Creates: output/DataUriCss.html
}
}
```
--------------------------------
### Advanced PNG Optimization with Options
Source: https://context7.com/depsypher/pngtastic/llms.txt
Performs advanced PNG optimization using Pngtastic, with options to remove gamma correction and set a specific compression level. It also retrieves and displays detailed optimization results.
```java
import com.googlecode.pngtastic.core.PngImage;
import com.googlecode.pngtastic.core.PngOptimizer;
import com.googlecode.pngtastic.core.PngOptimizer.OptimizerResult;
import java.util.List;
public class AdvancedOptimizationExample {
public static void main(String[] args) throws Exception {
// Create optimizer with debug logging
PngOptimizer optimizer = new PngOptimizer("debug");
// Load image
PngImage image = new PngImage("/path/to/input.png", "debug");
// Optimize with options:
// - removeGamma: true to strip gamma correction
// - compressionLevel: 9 for maximum compression (0-9, null tries all)
boolean removeGamma = true;
Integer compressionLevel = 9;
// Optimize and save to file
optimizer.optimize(image, "/path/to/output.png", removeGamma, compressionLevel);
// Process results
List results = optimizer.getResults();
for (OptimizerResult result : results) {
long saved = result.getOriginalFileSize() - result.getOptimizedFileSize();
double percent = (saved * 100.0) / result.getOriginalFileSize();
System.out.printf("Saved %d bytes (%.2f%%)%n", saved, percent);
}
}
}
```
--------------------------------
### Analyze Colors with Timeout
Source: https://context7.com/depsypher/pngtastic/llms.txt
Perform color analysis with a specified timeout to handle large images safely.
```java
import com.googlecode.pngtastic.core.PngColorCounter;
import com.googlecode.pngtastic.core.PngException;
import com.googlecode.pngtastic.core.PngImage;
public class ColorCountingWithTimeoutExample {
public static void main(String[] args) throws Exception {
// Create counter with 5 second timeout
double distThreshold = 0.005;
double freqThreshold = 0.0005;
int minAlpha = 30;
long timeout = 5000; // 5 seconds in milliseconds
PngColorCounter counter = new PngColorCounter(distThreshold, freqThreshold, minAlpha, timeout);
try {
PngImage image = new PngImage("/path/to/large-image.png", "info");
counter.count(image);
System.out.println(counter.getResult());
} catch (PngException e) {
if (e.getMessage().contains("timeout")) {
System.err.println("Color counting timed out after " + timeout + "ms");
} else {
throw e;
}
}
}
}
```
--------------------------------
### Count Dominant Colors in PNG
Source: https://context7.com/depsypher/pngtastic/llms.txt
Analyze dominant colors in PNG images from the command line, setting thresholds for distance, frequency, and minimum alpha.
```bash
java -cp target/pngtastic-1.8-SNAPSHOT.jar \
com.googlecode.pngtastic.PngtasticColorCounter \
--distThreshold 0.005 \
--freqThreshold 0.0005 \
--minAlpha 30 \
--timeout 10000 \
--logLevel info \
image.png
```
--------------------------------
### Ant Task for Generating CSS Data URIs
Source: https://context7.com/depsypher/pngtastic/llms.txt
Utilize the Pngtastic Ant task to generate CSS files with data URIs for small PNG icons, optimizing for web use.
```xml
```
--------------------------------
### CLI PngtasticLayerer
Source: https://context7.com/depsypher/pngtastic/llms.txt
Composites multiple PNG images into a single layered image.
```APIDOC
## CLI PngtasticLayerer
### Description
Composite multiple PNG images from the command line to create layered images.
### Method
CLI Execution
### Parameters
#### Options
- **--toDir** (string) - Required - Output directory
- **--outFile** (string) - Required - Output filename
- **--compressionLevel** (integer) - Optional - Compression level 0-9
- **--logLevel** (string) - Optional - Logging: none, debug, info, or error
```
--------------------------------
### PngLayerer Image Compositing
Source: https://context7.com/depsypher/pngtastic/llms.txt
Composite PNG images by layering them. The foreground layer requires an alpha channel for transparency. Specify compression level and concurrency for the layering process.
```java
import com.googlecode.pngtastic.core.PngImage;
import com.googlecode.pngtastic.core.PngLayerer;
import java.io.ByteArrayOutputStream;
public class ImageLayeringExample {
public static void main(String[] args) throws Exception {
// Create layerer
PngLayerer layerer = new PngLayerer("info");
// Load base (background) image
PngImage baseImage = new PngImage("/path/to/background.png", "info");
// Load layer (foreground) image - must have alpha channel
PngImage layerImage = new PngImage("/path/to/foreground.png", "info");
// Composite the images
// compressionLevel: null to try all, or 0-9
// concurrent: false for single-threaded processing
Integer compressionLevel = null;
boolean concurrent = false;
PngImage result = layerer.layer(baseImage, layerImage, compressionLevel, concurrent);
// Export the composited image
ByteArrayOutputStream outputBytes = new ByteArrayOutputStream();
result.writeDataOutputStream(outputBytes);
result.export("/path/to/composited.png", outputBytes.toByteArray());
}
}
```
--------------------------------
### CLI PngtasticColorCounter
Source: https://context7.com/depsypher/pngtastic/llms.txt
Analyzes dominant colors in PNG images.
```APIDOC
## CLI PngtasticColorCounter
### Description
Analyze dominant colors in PNG images from the command line.
### Method
CLI Execution
### Parameters
#### Options
- **--distThreshold** (float) - Optional - Color distance threshold 0.0-1.0
- **--freqThreshold** (float) - Optional - Minimum frequency threshold 0.0-1.0
- **--minAlpha** (integer) - Optional - Minimum alpha value 0-255
- **--timeout** (integer) - Optional - Timeout in milliseconds
- **--logLevel** (string) - Optional - Logging: none, debug, info, or error
```
--------------------------------
### PngImage Class - Loading and Accessing Properties
Source: https://context7.com/depsypher/pngtastic/llms.txt
The PngImage class is used to load PNG images from various sources and access their metadata properties.
```APIDOC
## PngImage Class
### Description
Represents a PNG image and provides constructors for loading images from files, input streams, or byte arrays.
### Methods
- **new PngImage(String path, String logLevel)**: Loads image from file path.
- **new PngImage(InputStream stream)**: Loads image from an input stream.
- **new PngImage(byte[] bytes)**: Loads image from a byte array.
- **getWidth()**: Returns image width.
- **getHeight()**: Returns image height.
- **getBitDepth()**: Returns image bit depth.
- **getColorType()**: Returns image color type.
- **getInterlace()**: Returns image interlace setting.
```
--------------------------------
### Add Pngtastic Dependency
Source: https://github.com/depsypher/pngtastic/blob/master/README.md
Include the Pngtastic library in your Maven project configuration.
```xml
com.github.depsypher
pngtastic
1.7
```
--------------------------------
### Analyze Dominant Colors
Source: https://context7.com/depsypher/pngtastic/llms.txt
Identify dominant colors in a PNG image using configurable thresholds for distance, frequency, and alpha transparency.
```java
import com.googlecode.pngtastic.core.PngColorCounter;
import com.googlecode.pngtastic.core.PngColorCounter.ColorCounterResult;
import com.googlecode.pngtastic.core.PngImage;
import com.googlecode.pngtastic.core.PngPixel;
import java.util.List;
public class ColorCountingExample {
public static void main(String[] args) throws Exception {
// Create color counter with thresholds:
// distThreshold: 0.01 - colors within 1% distance are considered similar
// freqThreshold: 0.01 - colors must appear in at least 1% of pixels
// minAlpha: 30 - ignore nearly transparent pixels (alpha < 30)
double distThreshold = 0.01;
double freqThreshold = 0.01;
int minAlpha = 30;
PngColorCounter counter = new PngColorCounter(distThreshold, freqThreshold, minAlpha);
// Load and analyze image
PngImage image = new PngImage("/path/to/image.png", "info");
counter.count(image);
// Get results
ColorCounterResult result = counter.getResult();
System.out.println("Image: " + result.getFileName());
System.out.println("Dimensions: " + result.getWidth() + "x" + result.getHeight());
System.out.println("Total candidate colors: " + result.getTotalColors());
System.out.println("Dominant colors found: " + result.getDominantColors().size());
System.out.println("Processing time: " + result.getElapsed() + "ms");
// Iterate over dominant colors
List dominantColors = result.getDominantColors();
for (PngPixel pixel : dominantColors) {
System.out.printf("RGB(%d, %d, %d) - frequency: %d%n",
pixel.getRed(), pixel.getGreen(), pixel.getBlue(), pixel.getFreq());
}
}
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.