Scrimage Documentation

repository·master·Indexed 22 days ago

https://github.com/sksamuel/scrimage

A high-performance, immutable, and functional JVM library for image manipulation. Scrimage provides a simple API for resizing, filtering, and format conversion, featuring the ImmutableImage core data type. It supports advanced operations such as autocropping, brightness adjustment, image similarity measurement via RMSE, and comprehensive support for reading and writing animated GIFs and WebP files.

Tokens
17.6K
Snippets
82
Records
102
Agent score
78%

What's inside Scrimage

  1. Overview of Scrimage

    master

    Scrimage is an immutable, functional, and performant JVM library designed for image manipulation. It provides a concise API for common tasks such as resizing, format conversion, applying filters, and managing metadata.

    It is ideal for use cases like:

    • Creating thumbnails for web applications.
    • Standardizing product image dimensions.
    • Optimizing PNG uploads via compression.
    • Applying visual filters (e.g., grayscale).

    Note: It is not intended for advanced computer vision tasks like face recognition or movement tracking. It builds upon java.awt.* and integrates with metadata-extractor and TwelveMonkeys.

  2. Understand the ImmutableImage core data type

    master
    The fundamental data type in Scrimage is the ImmutableImage class. Unlike standard Java AWT images which are mutable, ImmutableImage wraps a Java AWT image and ensures that all operations return a new copy of the image rather than mutating the original instance. This makes image processing pipelines safer and more predictable.
  3. Compare cover and fit operations

    master

    When resizing images, choose between cover and fit based on how you want to handle aspect ratio mismatches:

    • cover: Scales the image so the entire target area is filled. This results in no empty space but causes parts of the source image to be cropped if the aspect ratios don't match.
    • fit: Scales the image so the entire source image is visible within the target area. This prevents cropping but results in empty 'background' space (letterboxing/pillarboxing) if the aspect ratios don't match.
  4. Automatically correct image orientation

    master
    Scrimage automatically detects and corrects image orientation based on metadata flags (e.g., orientation flags used by mobile devices like iPhones). If an image is saved as landscape with a portrait flag, Scrimage will rotate the image data to match the intended orientation during loading.
  5. Difference between max() and fit()

    master

    When scaling an image to a target bounding box, choose between max() and fit() based on whether you need the output dimensions to be exact:

    1. max(width, height): Scales the image to the largest possible size that fits within the bounds without exceeding them. The output dimensions may be smaller than the requested width/height to preserve the aspect ratio without padding.
    2. fit(width, height): Scales the image to the largest possible size that fits within the bounds, but then pads the canvas with a background color so the final output matches the requested width and height exactly.
  6. Use Scrimage color spaces and conversions

    master

    While many Scrimage functions accept java.awt.Color, Scrimage provides a more flexible com.sksamuel.scrimage.color.Color interface. This interface supports multiple color spaces, including RGB, CMYK, Grayscale, HSL, and HSV.

    You can convert between these color spaces using conversion methods like .toHSV() or .toRGB().

    // Convert RGB to HSV
    new RGBColor(255, 0, 255).toHSV();
    
    // Convert HSL to RGB
    new HSLColor(100f, 0.5f, 0.3f, 1f).toRGB();
  7. Resize the canvas dimensions

    master

    The resize operations in Scrimage change the dimensions of the canvas the image sits on. Unlike scaling, this operation behaves as follows:

    • If the new size is larger: The image is padded with a background color.
    • If the new size is smaller: The image is cropped.

    This is the primary method used when you want to perform a crop operation. You can anchor the source image to a specific position within the new canvas using Position constants.

  8. Read image metadata in Scrimage

    master

    Scrimage provides metadata reading capabilities built on top of the metadata-extractor project. You can access metadata in two ways:

    1. From an existing image instance: If the image was loaded from a stream, file, or resource, the metadata is attached to the image. Access it via image.metadata.
    2. Directly from a source without creating an image: Use the static methods on the ImageMetadata class (e.g., ImageMetadata.fromStream(stream)) to extract metadata without the overhead of full image instantiation.

    Once you have an ImageMetadata object, you can explore the data using .directories() or .tags().

    // Accessing metadata directly from a stream without creating an Image instance
    ImageMetadata meta = ImageMetadata.fromStream(stream);
    
    // Iterating through all tags
    Arrays.stream(meta.tags()).forEach(tag -> System.out.println(tag));
  9. What are Transforms in Scrimage

    master
    A Transform modifies an image and returns a new image derived from the input. While similar to a filter, a Transform is more powerful because it can return an entirely new image (e.g., changing dimensions or adding backgrounds) rather than just modifying existing pixels.
  10. Use the fit operation to scale images within a canvas

    master

    The fit operation scales an image to be as large as possible within the specified target dimensions without losing any part of the original image.

    Key behaviors:

    • Aspect Ratio Mismatch: If the source and target aspect ratios differ, the image will not cover the entire canvas. The excess area is filled with a background color.
    • Canvas Sizing: Unlike max, fit always returns an image with the exact dimensions specified, padding the canvas if necessary. Unlike cover, fit ensures no part of the source image is lost, even if it means leaving background padding.
    • Defaults: If not specified, the background color is transparent, the scaling method is ScaleMethod.Bicubic, and the image is positioned at Position.Center.
    // Example usage with target dimensions and a background color
    image.fit(400, 300, Color.DARK_GRAY);
  11. How composites work in Scrimage

    master

    A composite merges two images by applying a specific pixel-wise rule provided by a composite class. The operation takes an initial image and merges it with a second image using the chosen rule.

    Note on order: The effect of the composite depends on the order of the images. If you reverse the order of image1 and image2, the resulting visual effect will also be reversed.

  12. Write animated WebP files

    master

    To create an animated WebP, use StreamingWebpWriter. The process involves three steps:

    1. Configure the writer: Set global settings like frame delay and looping behavior.
    2. Prepare the stream: Open a WebpStream by specifying an output path or stream.
    3. Write frames: Add ImmutableImage objects to the stream. You can use the global delay or override it per frame.

    Important: WebpStream implements AutoCloseable. You must close the stream (ideally using try-with-resources) to ensure the buffered frames are encoded and written to the destination.

    Note: Browsers have minimum frame delay limits (e.g., ~0.2s for Chrome/Firefox, ~0.6s for Safari). If your delay is lower than these limits, the browser may revert to its own default delay.

    // 1. Configure
    StreamingWebpWriter writer = new StreamingWebpWriter()
       .withFrameDelay(Duration.ofSeconds(2))
       .withInfiniteLoop(true);
    
    // 2. Prepare and 3. Write (using try-with-resources)
    try (StreamingWebpWriter.WebpStream webp = writer.prepareStream("/path/to/animated.webp")) {
       webp.writeFrame(image0);
       webp.writeFrame(image1, Duration.ofMillis(500)); // Override delay for this frame
       webp.writeFrame(imageN);
    }