### Decode PNG Image with PngDecoder Source: https://github.com/brendan-duncan/image/blob/main/doc/formats.md Use PngDecoder to validate, decode, or get information about PNG files. 'startDecode' retrieves metadata without decoding image data. Access format-specific info via derived classes like PngInfo. ```dart final decoder = PngDecoder(); // Returns true if the file is a valid PNG image. decoder.isValidFile(fileBytes); // Decodes the PNG image, returning null if the file is not a PNG. Image? image = decoder.decode(fileBytes); // startDecode will decode just the information from the image file without decoding the image data. DecodeInfo? info = decoder.startDecode(fileBytes); if (info != null) { int width = info.width; // The width of the PNG image. int height = info.height; // The height of the PNG image. int numFrames = info.numFrames; // The number of frames, if it's an animated image, otherwise 1. final pngInfo = info as PngInfo; // The actual class of the info, in the case of PngDecoder. double? gamma = pngInfo.gamma; // The display gamma of the PNG int bits = pngInfo.bits; // How many bits per pixel for the PNG image data. } int numFrames = decoder.numFrames; // How many frames can be decoded. Image? frame0 = decoder.decodeFrame(0); // Decode the 1st frame if it's animated, otherwise the image itself. ``` -------------------------------- ### Iterate Over Pixels within a Pixel Object Source: https://github.com/brendan-duncan/image/blob/main/doc/image_data.md A Pixel object itself can act as an iterator to process pixels starting from a specific pixel and continuing to the end of its row. Useful for row-wise operations starting from a given point. ```dart // Get the first pixel of the last row from the image. final pixel = image.getPixel(0, image.height - 1); do { pixel.a = 0; // Set the alpha to 0, making it transparent } while (pixel.moveNext()); // Iterate for the remaining pixels of the image. ``` -------------------------------- ### Command Execution Source: https://github.com/brendan-duncan/image/blob/main/doc/commands.md Demonstrates how to chain image commands and execute them either synchronously on the main thread or asynchronously in a separate Isolate thread. ```APIDOC ## Command Execution ### Description Chain multiple image processing commands and execute them. Commands can be run on the main thread or in a separate Isolate thread for performance. ### Usage ```dart final cmd = Command() ..decodePngFile('image.png') ..sepia(amount: 0.5) ..vignette() ..writeToFile('processedImage.png'); // Execute in a separate Isolate thread await cmd.executeThread(); // Execute on the main thread (still async due to file IO) await cmd.execute(); ``` ### Retrieving Processed Image ```dart // Get the processed image after execution Image? image = await cmd.getImage(); // Get the processed image by executing in an Isolate thread if not already executed Image? image = await cmd.getImageThread(); ``` ### Retrieving Processed Bytes ```dart // Get the bytes of the encoded image after execution Uint8List? bytes = await cmd.getBytes(); // Get the bytes by executing in an Isolate thread if not already executed Uint8List? bytes = await cmd.getBytesThread(); ``` ``` -------------------------------- ### fillFlood Source: https://github.com/brendan-duncan/image/blob/main/doc/draw.md Fills a contiguous area of an image with a specified color, starting from a seed point. ```APIDOC ## fillFlood ### Description Performs a flood fill operation starting from the specified coordinates (`x`, `y`) with the given color. The fill spreads to contiguous pixels that match the starting pixel's color within a given threshold. Supports optional masking. ### Method `fillFlood` ### Parameters - `src` (Image) - The image to perform the flood fill on. - `x` (int) - The starting x-coordinate. - `y` (int) - The starting y-coordinate. - `color` (Color) - The color to fill with. - `threshold` (num) - The color similarity threshold for spreading the fill (default: 0.0). - `compareAlpha` (bool) - Whether to compare the alpha channel when determining similarity (default: `false`). - `mask` (Image?) - An optional mask image. - `maskChannel` (Channel) - The channel of the mask to use (default: `Channel.luminance`). ``` -------------------------------- ### Load Everything in Flutter Source: https://github.com/brendan-duncan/image/wiki/How-to-run-this-plugin-in-Flutter Initiates the process of requesting the app's documents directory and making a receipt image. It updates the UI once the image is ready. ```dart Future _loadEverything() async { await _requestAppDocumentsDirectory(); // TODO: 2 - GET APP DOCUMENTS DIRECTORY _dekontExist = await makeReceiptImage(); // TODO: 3 - MAKE A RECEIPT // Show the writen image if (_dekontExist == true) { setState(() { newDekontImage = _appDocumentsDirectory + "/" + widget._currentUserReceiptNo + ".jpg"; imageOkay = true; // FOR - 4 - MAIN WIDGET BUILD }); } } ``` -------------------------------- ### Get Pixel Coordinates and Dimensions Source: https://github.com/brendan-duncan/image/blob/main/doc/image_data.md Access the x and y coordinates, width, and height of the image a pixel belongs to. ```dart print(pixel.x); // The x coordinate of the pixel. print(pixel.y); // The y coordinate of the pixel. print(pixel.width); // The width of the image the pixel belongs to. print(pixel.height); // The height of hte image the pixel belongs to. ``` -------------------------------- ### Load and Draw Text with Bitmap Font Source: https://github.com/brendan-duncan/image/blob/main/doc/fonts.md Demonstrates how to load a bitmap font from a zip file and draw text onto an image. Ensure the font zip file is correctly generated and accessible. ```dart import 'package:image/image.dart' as img; void main() async { final fontZipFile = await File('font.zip').readAsBytes(); final font = img.BitmapFont.fromZip(fontZipFile); final image = img.Image(width: 320, height: 200); img.drawString(image, 'Hello', font: font, x: 10, y: 100); await img.encodePngFile('testFont.png', image); } ``` -------------------------------- ### Create, Draw Text, and Save PNG Image Source: https://github.com/brendan-duncan/image/blob/main/doc/tutorial.md Creates a new image, fills it with a color, draws text and a line, applies a blur, and saves the result as a PNG file. This uses the Command API for a sequence of operations. ```dart import 'package:image/image.dart' as img; void main() async { await (img.Command() // Create an image, with the default uint8 format and default number of channels, 3. ..createImage(width: 256, height: 256) // Fill the image with a solid color (blue) ..fill(color: img.ColorRgb8(0, 0, 255)) // Draw some text using the built-in 24pt Arial font ..drawString('Hello World', font: img.arial24, x: 0, y: 0) // Draw a red line ..drawLine(x1: 0, y1: 0, x2: 256, y2: 256, color: img.ColorRgb8(255, 0, 0), thickness: 3) // Blur the image ..gaussianBlur(radius: 10) // Save the image to disk as a PNG. ..writeToFile('test.png')) // Execute the command sequence. .execute(); } ``` -------------------------------- ### Fill Flood Source: https://github.com/brendan-duncan/image/blob/main/doc/draw.md Fills a contiguous area of an image with a specified color, starting from a seed point. Supports thresholding and masking. ```dart Image fillFlood(Image src, { required int x, required int y, required Color color, num threshold = 0.0, bool compareAlpha = false, Image? mask, Channel maskChannel = Channel.luminance }) ``` -------------------------------- ### PNG Encoder Usage Source: https://github.com/brendan-duncan/image/blob/main/doc/formats.md Demonstrates how to use the PngEncoder class to encode an Image object into PNG format. ```APIDOC ## PngEncoder ### Description Provides methods to encode an Image object into the PNG format. ### Methods - **encode(Image image)**: Encodes the given Image object to the PNG format, returning the encoded bytes. ### Properties - **supportsAnimation**: bool - Indicates whether the encoder supports encoding multi-frame images. ``` -------------------------------- ### Fill Flood Command Source: https://github.com/brendan-duncan/image/blob/main/doc/commands.md Performs a flood fill operation starting from a given point with a specified color. Supports thresholding and alpha comparison. ```dart void fillFlood({ required int x, required int y, required Color color, num threshold = 0.0, bool compareAlpha = false, Command? mask, Channel maskChannel = Channel.luminance }); ``` -------------------------------- ### Image Class Properties and Methods Source: https://github.com/brendan-duncan/image/blob/main/doc/image_data.md This snippet demonstrates how to access various properties of an Image object and use methods for data retrieval and manipulation, including channel remapping. ```APIDOC ## Image Data Properties and Methods ### Description Access properties like format, bits per pixel, row stride, and buffer. Use methods to get pixel data as `Uint8List`, optionally remapping channels, and to remap channels in-place. ### Methods #### `Image.fromBytes(..., ChannelOrder order)` Creates an Image from a byte list, optionally specifying the channel order of the incoming data. #### `Image.getBytes({ChannelOrder? order})` Returns the image data as a `Uint8List`. If an `order` is specified, it returns a new byte buffer with the channels rearranged. #### `Image.remapChannels(ChannelOrder order)` Remaps the colors of the Image to the requested order in-place. ### Properties - **`format`** (Format) - The format of the image data. - **`bitsPerPixel`** (int) - The number of bits per channel. - **`rowStride`** (int) - The number of bytes for a single row of pixels. - **`lengthInBytes`** (int) - The number of bytes to store all pixel data. - **`buffer`** (ByteBuffer) - The buffer used to store the pixel data. - **`numChannels`** (int) - The number of channels per pixel. If the Image has a palette, this is the number of palette color channels. - **`isLdrFormat`** (bool) - Indicates if the pixel format is a low dynamic range format. - **`isHdrFormat`** (bool) - Indicates if the pixel format is a high dynamic range format. - **`maxChannelValue`** (num) - The maximum value of a pixel channel. ### Code Examples ```dart // Accessing properties Format format = image.format; int bpp = image.bitsPerPixel; int stride = image.rowStride; int size = image.lengthInBytes; ByteBuffer buffer = image.buffer; // Getting pixel data Uint8List bytes = image.toUint8List(); Uint8List remappedBytes = image.getBytes(order: ChannelOrder.abgr); // Remapping channels in-place image.remapChannels(ChannelOrder.bgra); Uint8List remappedInPlaceBytes = image.getBytes(); // Other properties int numChannels = image.numChannels; bool isLdr = image.isLdrFormat; bool isHdr = image.isHdrFormat; num maxValue = image.maxChannelValue; ``` ``` -------------------------------- ### Calculate Pixel Luminance (Grayscale) Source: https://github.com/brendan-duncan/image/blob/main/doc/image_data.md Calculate the luminance (brightness or grayscale value) of a pixel's color. Also, get the normalized luminance. ```dart pixel.r = 128; pixel.g = 255; pixel.b = 40; print(pixel.luminance); // The luminance of the color is 192 print(pixel.luminanceNormalized); // The normalized luminance of the color is approximately 0.75. ``` -------------------------------- ### Create and Save an Image in Dart Source: https://github.com/brendan-duncan/image/blob/main/README.md Creates a new image, sets pixel values to create a gradient, and saves it as a PNG file. Ensure the 'image' package is imported. ```dart import 'dart:io'; import 'package:image/image.dart' as img; void main() async { // Create a 256x256 8-bit (default) rgb (default) image. final image = img.Image(width: 256, height: 256); // Iterate over its pixels for (var pixel in image) { // Set the pixels red value to its x position value, creating a gradient. pixel..r = pixel.x // Set the pixels green value to its y position value. ..g = pixel.y; } // Encode the resulting image to the PNG image format. final png = img.encodePng(image); // Write the PNG formatted data to a file. await File('image.png').writeAsBytes(png); } ``` -------------------------------- ### Vignette Command Source: https://github.com/brendan-duncan/image/blob/main/doc/commands.md Applies a vignette effect to the image, darkening or lightening the edges. Parameters control the start and end points of the effect, color, and amount. Masking is supported. ```dart void vignette({ num start = 0.3, num end = 0.75, Color? color, num amount = 0.8, Command? mask, Channel maskChannel = Channel.luminance }); ``` -------------------------------- ### Access Palette Image Index Source: https://github.com/brendan-duncan/image/blob/main/doc/image_data.md For palette images, get or set the pixel's index value in the palette. If the image is not a palette image, this accesses the red channel. ```dart print(pixel.index); // Will print the index value of the pixel if the image has a palette, otherwise the red channel. pixel.index = 5; // Will set the index value of hte pixel if the image has a palette, otherwise the red channel. ``` -------------------------------- ### Main Widget Build in Flutter Source: https://github.com/brendan-duncan/image/wiki/How-to-run-this-plugin-in-Flutter Builds the main UI for the receipt screen, including an AppBar and a body that displays either a loading indicator or the generated receipt image. ```dart @override Widget build(BuildContext context) { capitalHeight = MediaQuery.of(context).size.height; capitalWidth = MediaQuery.of(context).size.width; return Scaffold( resizeToAvoidBottomPadding: true, appBar: AppBar( title: Text("Customer Receipt"), backgroundColor: const Color(0xFF7CB342), elevation: 0.0, actions: [ Container( padding: EdgeInsets.only(right: 10.0), child: Icon(Icons.mail), ) ], ), body: Center( child: Container( margin: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0), width: capitalWidth, height: capitalHeight / 2.3, color: Colors.black54, child: imageOkay == true ? Container( width: capitalWidth - 20.0, height: capitalHeight / 2.3, child: Image.file(File('$newDekontImage')), ) : CircularProgressIndicator(), ), ), ); } ``` -------------------------------- ### Load, Resize, and Save Image Thumbnail in Dart Source: https://github.com/brendan-duncan/image/blob/main/README.md Asynchronously loads an image file, resizes it to a thumbnail, and saves it. The image commands are executed on an isolate thread for performance if supported. Accepts an optional file path as a command-line argument. ```dart import 'package:image/image.dart' as img; void main(List args) async { final path = args.isNotEmpty ? args[0] : 'test.png'; final cmd = img.Command() // Decode the image file at the given path ..decodeImageFile(path) // Resize the image to a width of 64 pixels and a height that maintains the aspect ratio of the original. ..copyResize(width: 64) // Write the image to a PNG file (determined by the suffix of the file path). ..writeToFile('thumbnail.png'); // On platforms that support Isolates, execute the image commands asynchronously on an isolate thread. // Otherwise, the commands will be executed synchronously. await cmd.executeThread(); } ``` -------------------------------- ### Access Normalized Pixel Channel Values Source: https://github.com/brendan-duncan/image/blob/main/doc/image_data.md Get and set pixel channel values using normalized ranges [0, 1]. This simplifies color translation between different formats. ```dart pixel.r = 51; final rn = pixel.rNormalized; // rNormalized will be 0.2 (51/255) pixel.rNormalized = 0.5; // Set the normalized value of the red channel. The red value will be 127 (0.5 * 255).floor(). ``` -------------------------------- ### Chaining Image Commands Source: https://github.com/brendan-duncan/image/blob/main/doc/commands.md Demonstrates chaining multiple image manipulation commands. Commands are only invoked when execute() or executeThread() is called. execute() is async due to potential file IO. ```dart final cmd = Command() // Creates a Command object, which doesn't do anything itself. // Add a decodePngFile sub-command to the Command object ..decodePngFile('image.png') // Add a vignette sub-command, which gets its input from the previous sub-command ..vignette() // Add a writeToFile sub-command, which gets its input from the previous sub-command. ..writeToFile('processedImage.png'); ``` ```dart await cmd.execute(); ``` ```dart Image? image = await cmd.getImage(); ``` ```dart Image? image = await cmd.getImageThread(); ``` ```dart Uint8List? bytes = await cmd.getBytes(); ``` ```dart Uint8List? bytes = await cmd.getBytesThread(); ``` ```dart await (Command() ..decodePngFile('image1.png') ..sepia() ..writeToFile('image1_out.png') ..decodeImageFile('image2.png') ..sketch() ..writeToFile('image2_out.png')) .execute(); ``` -------------------------------- ### Access and Modify Pixel Channel Values Source: https://github.com/brendan-duncan/image/blob/main/doc/image_data.md Get and set individual channel values (red, green, blue, alpha) of a pixel using direct properties or index access. Also, iterate through channels. ```dart pixel.r = 120; // Set the red channel of the pixel. pixel.g = 50; // Set the green channel of the pixel. pixel.b = 75; // Set the blue channel of the pixel. pixel.a = 255; // Set the alpha channel of the pixel. print(pixel.length); // The number of channels for the pixel pixel[1] = 50; // Sets the green (index 1) channel of the pixel. for (final ch in pixel) { print(ch); // Will print 120, 50, 75, 255 } print(pixel.maxChannelValue); // Will print the max value of a channel for the pixel format. For uint8, it will be 255. ``` -------------------------------- ### PNG Decoder Usage Source: https://github.com/brendan-duncan/image/blob/main/doc/formats.md Demonstrates how to use the PngDecoder class to validate, decode, and extract information from PNG image files. ```APIDOC ## PngDecoder ### Description Provides methods to validate, decode, and extract detailed information from PNG image files. ### Methods - **isValidFile(Uint8List fileBytes)**: Returns true if the file is a valid PNG image. - **decode(Uint8List fileBytes)**: Decodes the PNG image, returning an Image object or null if the file is not a PNG. - **startDecode(Uint8List fileBytes)**: Decodes only the information from the image file without decoding the image data, returning a DecodeInfo object or null. - **decodeFrame(int frameIndex)**: Decodes a specific frame from an animated image. ### Properties - **numFrames**: int - The number of frames that can be decoded. ### DecodeInfo (PngInfo) #### Properties - **width**: int - The width of the PNG image. - **height**: int - The height of the PNG image. - **numFrames**: int - The number of frames, if it's an animated image, otherwise 1. - **gamma**: double? - The display gamma of the PNG. - **bits**: int - How many bits per pixel for the PNG image data. ``` -------------------------------- ### Manipulate Palette Colors Source: https://github.com/brendan-duncan/image/blob/main/doc/image_data.md Access and modify the colors within an image's palette. This includes getting the number of colors, channels, format, and individual color channel values, as well as setting specific channel values or entire RGBA colors. ```dart final palette = image.palette; if (palette != null) { int numColors = palette.numColors; // The number of colors stored by the palette int numChannels = palette.numChannels; // The number of channels per color. Format format = palette.format; // The color Format of the palette. num red = palette.getRed(0); // Get the value of the red channel of the 1st color in the palette. num green = palette.getGreen(0); // Get the value of the green channel of the 1st color in the palette. num blue = palette.getBlue(0); // Get the value of the blue channel of the 1st color in the palette. num alpha = palette.getAlpha(0); // Get the value of the alpha channel of the 1st color in the palette. green = palette.get(0, 1); // Get the green (1) channel of the 1st color of the palette. palette.set(0, 1, 42); // Set the green (1) channel of the 1st color of the palette. palette.setColor(0, 128, 42, 80, 255); // Set the RGBA 1st color of the palette. ``` -------------------------------- ### Image Creation Commands Source: https://github.com/brendan-duncan/image/blob/main/doc/commands.md Methods for creating and manipulating images within the Command API. ```APIDOC ## Image Creation Commands ### `image(Image image)` Use a specific Image object as the current image for subsequent commands. ### `createImage({ required int width, required int height, Format format = Format.uint8, int numChannels = 3, bool withPalette = false, Format paletteFormat = Format.uint8, Palette? palette, ExifData? exif, IccProfile? iccp, Map? textData })` Create a new image with the specified dimensions, format, and optional metadata. ### `convert({ int? numChannels, Format? format, num? alpha, bool withPalette = false })` Convert the current image by changing its format, number of channels, or alpha properties. ### `copy()` Create a duplicate of the current image. ### `addFrames(int count, AddFramesFunction callback)` Add animation frames to an image using a callback function that provides frames based on their index. ### `forEachFrame(FilterFunction callback)` Call a provided callback function for each frame of an animated image. ``` -------------------------------- ### Make Receipt Image in Flutter Source: https://github.com/brendan-duncan/image/wiki/How-to-run-this-plugin-in-Flutter Loads a template image, decodes it, draws text onto it, encodes it as JPEG, and saves it to the app's documents directory. Returns true upon successful creation. ```dart Future makeReceiptImage() async { // I use this as a template: // 'packages/mayApp/assets/images/CapitalReceipt.jpg' ByteData imageData = await rootBundle.load('packages/mayApp/assets/images/CapitalReceipt.jpg'); List bytes = Uint8List.view(imageData.buffer); Image _receiptImage = decodeImage(bytes); // TODO: WRITE ON TO THE IMAGE drawString(_receiptImage, arial_48, 440, 30, “Customer Receipt - Customer Name”, color: 0xFF000000); // Write it to disk as a different jpeg var new_jpeg = await encodeJpg(_receiptImage); String newDekontImage = _appDocumentsDirectory + "/" + "${_currentUserReceiptNo}" + ".jpg"; await File(newDekontImage).writeAsBytesSync(new_jpeg); return true; } ``` -------------------------------- ### Access Image Data Properties Source: https://github.com/brendan-duncan/image/blob/main/doc/image_data.md Retrieve various properties of the image data, such as its format, bits per pixel, row stride, total size in bytes, and the underlying buffer. Use `toUint8List()` for a direct byte view or `getBytes(order: ...)` to get data with a specified channel order. ```dart Format format = image.format; // The Format of the image data. int bpp = image.bitsPerPixel; // The number of bits per channel int stride = image.rowStride; // The number of bytes for a single row of pixels. int size = image.lengthInBytes; // The number of bytes to store all pixel data. ByteBuffer buffer = image.buffer; // The buffer used to store the pixel data. Uint8List bytes = image.toUint8List(); // A Uint8List view of the pixel data buffer. Uint8List bytes = image.getBytes(order: ChannelOrder.abgr); // Like toUint8List, but can remap the color channels. int numChannels = image.numChannels; // The number of channels per pixel. bool isLdr = image.isLdrFormat; // Is the pixel format a low dynamic range format? bool isHdr = image.isHdrFormat; // Is the pixel format a high dynamic range format? num maxValue = image.maxChannelValue; // The maximum value of a pixel channel. ``` -------------------------------- ### Create Images with Different Formats Source: https://github.com/brendan-duncan/image/blob/main/doc/image_data.md Instantiate `Image` objects with specified dimensions, channel counts, and color formats. Supports creating images with palettes and specific bit depths. ```dart // Create an image with the default uint8 format and default number of channels, 3. final rgb8 = Image(width: 256, height: 256); // Create an 8-bit rgba image. final rgba8 = Image(width: 256, height: 256, numChannels: 4); // Create an 8-bit image with an rgb palette. final rgbPalette = Image(width: 256, height: 256, withPalette: true); // Create an 8-bit image with an rgba palette. final rgbaPalette = Image(width: 256, height: 256, numChannels: 4, withPalette: true); // Create a 1-bit, 1-channel Image. final bitmap = Image(width: 256, height: 256, format: Format.uint1, numChannels: 1); // Create a 16-bit floating point rgba image. final float16Image = Image(width: 256, height: 256, format: Format.float16); ``` -------------------------------- ### Instantiate Dart Wasm Module Source: https://github.com/brendan-duncan/image/blob/main/web/filter_lab.html Fetches and compiles a Dart WebAssembly module, then instantiates it with necessary imports. Handles potential errors during fetching or instantiation. ```javascript (async function () { let dart2wasm_runtime; let moduleInstance; try { const dartModulePromise = WebAssembly.compileStreaming(fetch('filter_lab.wasm')); const imports = {}; dart2wasm_runtime = await import('./filter_lab.mjs'); moduleInstance = await dart2wasm_runtime.instantiate(dartModulePromise, imports); } catch (exception) { console.error(`Failed to fetch and instantiate wasm module: ${exception}`); console.error('See https://dart.dev/web/wasm for more information.'); } if (moduleInstance) { try { await dart2wasm_runtime.invoke(moduleInstance); } catch (exception) { console.error(`Exception while invoking test: ${exception}`); } } })(); ``` -------------------------------- ### Quantize Command Source: https://github.com/brendan-duncan/image/blob/main/doc/commands.md Reduces the number of colors in the image using a specified method and dither kernel. Supports serpentine dithering. ```dart void quantize({ int numberOfColors = 256, QuantizeMethod method = QuantizeMethod.neuralNet, DitherKernel dither = DitherKernel.none, bool ditherSerpentine = false }); ``` -------------------------------- ### Batch and Execute Image Commands Source: https://github.com/brendan-duncan/image/blob/main/doc/commands.md Chains multiple image processing commands and executes them. Use executeThread() for Isolate execution or execute() for main thread execution. File IO operations make execute() an async method. ```dart final cmd = Command() ..decodePngFile('image.png') ..sepia(amount: 0.5) ..vignette() ..writeToFile('processedImage.png'); // Nothing has actually been performed yet; // the commands have recorded the information necessary to execute later. const useIsolate = true; if (useIsolate) { await cmd.executeThread(); // Executes in a separate Isolate thread. } else { await cmd.execute(); // Executes in the main thread. It is still an async method because file IO is async. } ``` -------------------------------- ### trim Source: https://github.com/brendan-duncan/image/blob/main/doc/transform.md Returns a new Image with transparent borders removed. ```APIDOC ## trim ### Description Returns a new Image with transparent borders removed. ### Method Signature ```dart Image trim(Image src, { TrimMode mode = TrimMode.topLeftColor, Trim sides = Trim.all }) ``` ### Parameters - **src** (Image) - The image to trim. - **mode** (TrimMode) - Optional. The mode to use for trimming (default: TrimMode.topLeftColor). - **sides** (Trim) - Optional. The sides of the image to trim (default: Trim.all). ``` -------------------------------- ### Dither Image Command Source: https://github.com/brendan-duncan/image/blob/main/doc/commands.md Applies dithering to the image using a specified quantizer and dither kernel. Supports serpentine dithering. ```dart void ditherImage({ Quantizer? quantizer, DitherKernel kernel = DitherKernel.floydSteinberg, bool serpentine = false }); ``` -------------------------------- ### Load, Resize, and Save JPEG Thumbnail Source: https://github.com/brendan-duncan/image/blob/main/doc/tutorial.md Reads a JPEG image, resizes it to a specified width while maintaining aspect ratio, and saves it as a JPEG thumbnail. Ensure the input file exists and the output directory is writable. ```dart import 'dart:io'; import 'package:image/image.dart' as img; void main() { // Read a jpeg image from file. final image = img.decodeJpg(File('test.jpg').readAsBytesSync())!; // Resize the image to a 120x? thumbnail (maintaining the aspect ratio). final thumbnail = img.copyResize(image, width: 120); // Save the thumbnail to a jpeg file. img.encodeJpgFile('out/thumbnail-test.png', thumbnail); } ``` -------------------------------- ### General Decoder Utilities Source: https://github.com/brendan-duncan/image/blob/main/doc/formats.md Utility functions for finding and creating decoders based on data or file names. ```APIDOC ## General Decoder Utilities ### Description Provides utility functions to find the appropriate decoder for given image data or file names, and to create decoders for specific image formats. ### Methods - **findDecoderForData(Uint8List fileBytes)**: Determines the format of the given file and returns its Decoder. This attempts to decode the image with known decoders, returning the first one that supports the data. - **findDecoderForNamedImage(String filename)**: Returns the decoder based on the file name extension. - **findFormatForData(List data)**: Finds the [ImageFormat] for the given file data. - **createDecoderForFormat(ImageFormat format)**: Creates a [Decoder] for the given [ImageFormat] type. ``` -------------------------------- ### Auto-Trim Directory of Images Source: https://github.com/brendan-duncan/image/blob/main/doc/tutorial.md Loads all images from a specified directory, automatically determines trim boundaries from the first image (based on transparency), and applies these boundaries to trim all subsequent images. The trimmed images are saved with a 'trimmed-' prefix. ```dart import 'package:image/image.dart' as img; void main(List argv) { final path = argv[0]; final dir = Directory(path); final files = dir.listSync(); List trimRect; for (final f in files) { if (f is! File) { continue; } final bytes = f.readBytesSync(); final image = img.decodeImage(bytes); if (image == null) { continue; } if (trimRect == null) { trimRect = img.findTrim(image, mode: img.TrimMode.transparent); } final trimmed = img.copyCrop(image, x: trimRect[0], y: trimRect[1], width: trimRect[2], height: trimRect[3]); String name = f.uri.pathSegments.last; img.encodeImageFile('$path/trimmed-$name', trimmed); } } ``` -------------------------------- ### quantize Source: https://github.com/brendan-duncan/image/blob/main/doc/commands.md Quantizes the image to a specified number of colors using a chosen method and dithering option. ```APIDOC ## quantize ### Description Quantizes the image to a specified number of colors. ### Parameters - **numberOfColors** (int) - Default: 256 - The number of colors to quantize to. - **method** (QuantizeMethod) - Default: QuantizeMethod.neuralNet - The quantization method. - **dither** (DitherKernel) - Default: DitherKernel.none - The dithering kernel to use. - **ditherSerpentine** (bool) - Default: false - Whether to use serpentine order for dithering. ``` -------------------------------- ### Decode Image by Filename Extension Source: https://github.com/brendan-duncan/image/blob/main/doc/formats.md Determine the decoder to use based on the image file's extension. This function infers the format from the filename. ```dart Image? decodeNamedImage(String path, Uint8List data, { int? frame }); ``` -------------------------------- ### Contrast Command Source: https://github.com/brendan-duncan/image/blob/main/doc/commands.md Adjusts the contrast of the image. Requires a contrast value and supports masking. ```dart void contrast({ required num contrast, Command? mask, Channel maskChannel = Channel.luminance }); ``` -------------------------------- ### copyResize Source: https://github.com/brendan-duncan/image/blob/main/doc/transform.md Returns a resized copy of the source image. Aspect ratio can be maintained, and padding color can be specified. ```APIDOC ## copyResize ### Description Returns a resized copy of the src image. * If width is set but not height, height will be calculated to maintain the aspect ratio of src. * If height is set but not width, width will be calculated to maintain the aspect ratio of src. * If both width and height are set: * If maintainAspect is not set or is false, src will be stretched. * If maintainAspect is true, src will fill the new resolution without changing the aspect ratio, using backgroundColor as the padding color. ### Signature ```dart Image copyResize(Image src, { int? width, int? height, bool? maintainAspect, Color? backgroundColor, Interpolation interpolation = Interpolation.nearest }) ``` ``` -------------------------------- ### Encode Image to File by Name Source: https://github.com/brendan-duncan/image/blob/main/doc/formats.md Encode an image to a file format using its filename extension to determine the format. ```dart Uint8List? encodeNamedImage(String path, Image image); ``` -------------------------------- ### Trim Command Source: https://github.com/brendan-duncan/image/blob/main/doc/commands.md Trims transparent or opaque borders from the image. Specify the TrimMode and which sides to trim. ```dart void trim({ TrimMode mode = TrimMode.transparent, Trim sides = Trim.all }); ``` -------------------------------- ### Copy Resize Crop Square Command Source: https://github.com/brendan-duncan/image/blob/main/doc/commands.md Copies the image after resizing and cropping it into a square. Specify the desired size for the square. Supports rounded corners. ```dart void copyResizeCropSquare({ required int size, Interpolation interpolation = Interpolation.nearest, num radius = 0}); ``` -------------------------------- ### Copy Resize Command Source: https://github.com/brendan-duncan/image/blob/main/doc/commands.md Copies the image after resizing it. Specify the desired width and/or height. The interpolation method can also be set. ```dart void copyResize({ int? width, int? height, Interpolation interpolation = Interpolation.nearest }); ``` -------------------------------- ### quantize Source: https://github.com/brendan-duncan/image/blob/main/doc/filters.md Reduces the number of colors in an image to a specified count. Various quantization methods and dithering options are available. ```APIDOC ## quantize ### Description Reduces the number of colors in an image. ### Parameters - **src** (Image) - The source image. - **numberOfColors** (int) - The target number of colors (default: 256). - **method** (QuantizeMethod) - The quantization method (default: QuantizeMethod.neuralNet). - **dither** (DitherKernel) - The dithering kernel to use (default: DitherKernel.none). - **ditherSerpentine** (bool) - Whether to use serpentine dithering (default: false). ``` -------------------------------- ### Format Decoding / Encoding Commands Source: https://github.com/brendan-duncan/image/blob/main/doc/commands.md Commands for decoding and encoding various image formats. ```APIDOC ## decodeImage ### Description Decodes image data from a Uint8List. ### Method void ### Parameters - **data** (Uint8List) - The byte data of the image. ## decodeNamedImage ### Description Decodes image data from a Uint8List with a specified path. ### Method void ### Parameters - **path** (String) - The path associated with the image data. - **data** (Uint8List) - The byte data of the image. ## decodeImageFile ### Description Decodes an image directly from a file path. ### Method void ### Parameters - **path** (String) - The path to the image file. ## writeToFile ### Description Writes the current image data to a file. ### Method void ### Parameters - **path** (String) - The path to the file where the image will be written. ## decodeBmp ### Description Decodes BMP image data from a Uint8List. ### Method void ### Parameters - **data** (Uint8List) - The BMP image data. ## decodeBmpFile ### Description Decodes a BMP image directly from a file path. ### Method void ### Parameters - **path** (String) - The path to the BMP image file. ## encodeBmp ### Description Encodes the current image data into BMP format. ### Method void ## encodeBmpFile ### Description Encodes the current image data into BMP format and saves it to a file. ### Method void ### Parameters - **path** (String) - The path to save the BMP file. ## encodeCur ### Description Encodes the current image data into CUR format. ### Method void ## encodeCurFile ### Description Encodes the current image data into CUR format and saves it to a file. ### Method void ### Parameters - **path** (String) - The path to save the CUR file. ## decodeExr ### Description Decodes EXR image data from a Uint8List. ### Method void ### Parameters - **data** (Uint8List) - The EXR image data. ## decodeExrFile ### Description Decodes an EXR image directly from a file path. ### Method void ### Parameters - **path** (String) - The path to the EXR image file. ## decodeGif ### Description Decodes GIF image data from a Uint8List. ### Method void ### Parameters - **data** (Uint8List) - The GIF image data. ## decodeGifFile ### Description Decodes a GIF image directly from a file path. ### Method void ### Parameters - **path** (String) - The path to the GIF image file. ## encodeGif ### Description Encodes the current image data into GIF format. ### Method void ### Parameters - **samplingFactor** (int) - Optional. Sampling factor for encoding. - **dither** (DitherKernel) - Optional. Dithering kernel to use. - **ditherSerpentine** (bool) - Optional. Whether to use serpentine dithering. ## encodeGifFile ### Description Encodes the current image data into GIF format and saves it to a file. ### Method void ### Parameters - **path** (String) - The path to save the GIF file. - **samplingFactor** (int) - Optional. Sampling factor for encoding. - **dither** (DitherKernel) - Optional. Dithering kernel to use. - **ditherSerpentine** (bool) - Optional. Whether to use serpentine dithering. ## decodeIco ### Description Decodes ICO image data from a Uint8List. ### Method void ### Parameters - **data** (Uint8List) - The ICO image data. ## decodeIcoFile ### Description Decodes an ICO image directly from a file path. ### Method void ### Parameters - **path** (String) - The path to the ICO image file. ## encodeIco ### Description Encodes the current image data into ICO format. ### Method void ## encodeIcoFile ### Description Encodes the current image data into ICO format and saves it to a file. ### Method void ### Parameters - **path** (String) - The path to save the ICO file. ## decodeJpg ### Description Decodes JPG image data from a Uint8List. ### Method void ### Parameters - **data** (Uint8List) - The JPG image data. ## decodeJpgFile ### Description Decodes a JPG image directly from a file path. ### Method void ### Parameters - **path** (String) - The path to the JPG image file. ## encodeJpg ### Description Encodes the current image data into JPG format. ### Method void ### Parameters - **quality** (int) - Optional. The quality of the JPG encoding (0-100). ## encodeJpgFile ### Description Encodes the current image data into JPG format and saves it to a file. ### Method void ### Parameters - **path** (String) - The path to save the JPG file. - **quality** (int) - Optional. The quality of the JPG encoding (0-100). ## decodePng ### Description Decodes PNG image data from a Uint8List. ### Method void ### Parameters - **data** (Uint8List) - The PNG image data. ## decodePngFile ### Description Decodes a PNG image directly from a file path. ### Method void ### Parameters - **path** (String) - The path to the PNG image file. ## encodePng ### Description Encodes the current image data into PNG format. ### Method void ### Parameters - **level** (int) - Optional. The compression level (0-9). - **filter** (PngFilter) - Optional. The PNG filter type to use. ## encodePngFile ### Description Encodes the current image data into PNG format and saves it to a file. ### Method void ### Parameters - **path** (String) - The path to save the PNG file. - **level** (int) - Optional. The compression level (0-9). - **filter** (PngFilter) - Optional. The PNG filter type to use. ## decodePsd ### Description Decodes PSD image data from a Uint8List. ### Method void ### Parameters - **data** (Uint8List) - The PSD image data. ## decodePsdFile ### Description Decodes a PSD image directly from a file path. ### Method void ### Parameters - **path** (String) - The path to the PSD image file. ## decodePvr ### Description Decodes PVR image data from a Uint8List. ### Method void ### Parameters - **data** (Uint8List) - The PVR image data. ## decodePvrFile ### Description Decodes a PVR image directly from a file path. ### Method void ### Parameters - **path** (String) - The path to the PVR image file. ## encodePvr ### Description Encodes the current image data into PVR format. ### Method void ## encodePvrFile ### Description Encodes the current image data into PVR format and saves it to a file. ### Method void ### Parameters - **path** (String) - The path to save the PVR file. ## decodeTga ### Description Decodes TGA image data from a Uint8List. ### Method void ### Parameters - **data** (Uint8List) - The TGA image data. ## decodeTgaFile ### Description Decodes a TGA image directly from a file path. ### Method void ### Parameters - **path** (String) - The path to the TGA image file. ## encodeTga ### Description Encodes the current image data into TGA format. ### Method void ## encodeTgaFile ### Description Encodes the current image data into TGA format and saves it to a file. ### Method void ### Parameters - **path** (String) - The path to save the TGA file. ## decodeTiff ### Description Decodes TIFF image data from a Uint8List. ### Method void ### Parameters - **data** (Uint8List) - The TIFF image data. ## decodeTiffFile ### Description Decodes a TIFF image directly from a file path. ### Method void ### Parameters - **path** (String) - The path to the TIFF image file. ## encodeTiff ### Description Encodes the current image data into TIFF format. ### Method void ## encodeTiffFile ### Description Encodes the current image data into TIFF format and saves it to a file. ### Method void ### Parameters - **path** (String) - The path to save the TIFF file. ## decodeWebP ### Description Decodes WebP image data from a Uint8List. ### Method void ### Parameters - **data** (Uint8List) - The WebP image data. ## decodeWebPFile ### Description Decodes a WebP image directly from a file path. ### Method void ### Parameters - **path** (String) - The path to the WebP image file. ``` -------------------------------- ### fill Source: https://github.com/brendan-duncan/image/blob/main/doc/draw.md Fills an entire image with a specified color. ```APIDOC ## fill ### Description Fills the entire image with the specified color. Supports optional masking. ### Method `fill` ### Parameters - `image` (Image) - The image to fill. - `color` (Color) - The color to fill with. - `mask` (Image?) - An optional mask image. - `maskChannel` (Channel) - The channel of the mask to use (default: `Channel.luminance`). ``` -------------------------------- ### Grayscale Command Source: https://github.com/brendan-duncan/image/blob/main/doc/commands.md Converts the image to grayscale. The amount of effect can be controlled, and masking is supported. ```dart void grayscale({ num amount = 1, Command? mask, Channel maskChannel = Channel.luminance }); ```