Dart library for decoding/encoding image formats, and image processing.

Related tags

Templates image
Overview

image

Build Status

Overview

A Dart library providing the ability to load, save and manipulate images in a variety of different file formats.

The library is written entirely in Dart and has no reliance on dart:io, so it can be used for both server and web applications.

Performance Warning

Because this library is written entirely in Dart and is a not native executed library, its performance will not be as fast as a native library.

Supported Image Formats

Read/Write

  • PNG / Animated APNG
  • JPEG
  • Targa
  • GIF / Animated GIF
  • PVR(PVRTC)
  • ICO

Read Only

  • BMP
  • WebP / Animated WebP
  • TIFF
  • Photoshop PSD
  • OpenEXR

Write Only

  • CUR

Documentation

API

Examples

Format Decoding Functions

Example

Load an image asynchronously and resize it as a thumbnail.

import 'dart:io';
import 'dart:isolate';
import 'package:image/image.dart';

class DecodeParam {
  final File file;
  final SendPort sendPort;
  DecodeParam(this.file, this.sendPort);
}

void decodeIsolate(DecodeParam param) {
  // Read an image from file (webp in this case).
  // decodeImage will identify the format of the image and use the appropriate
  // decoder.
  var image = decodeImage(param.file.readAsBytesSync())!;
  // Resize the image to a 120x? thumbnail (maintaining the aspect ratio).
  var thumbnail = copyResize(image, width: 120);
  param.sendPort.send(thumbnail);
}

// Decode and process an image file in a separate thread (isolate) to avoid
// stalling the main UI thread.
void main() async {
  var receivePort = ReceivePort();

  await Isolate.spawn(
      decodeIsolate, DecodeParam(File('test.webp'), receivePort.sendPort));

  // Get the processed image from the isolate.
  var image = await receivePort.first as Image;

  await File('thumbnail.png').writeAsBytes(encodePng(image));
}
Comments
  • [question] Single band tiff with colortable

    [question] Single band tiff with colortable

    Hello, I would like to visualize single band tiff (an example would be a digital elevation model map that contains floating point values of the elevation in the pixel positions). The "image" doesn't have an internal colortable, but would come with a sidecar file describing it.

    I was wondering if it is possible to visualize such a file and if yes, what would be the best way to plug into the image production to apply the colortable and transform from physical value to color pixel.

    Thanks for any information you might throw in.

    opened by moovida 36
  • RangeError

    RangeError

    I get this error with a few images (very few out of thousands, but it keeps coming up), none of which appear to have any issues when opened in other applications: It occurs when I try to read the file.

    RangeError (index): Invalid value: Only valid value is 0: 1
    #0      List.[] (dart:core-patch/growable_array.dart:151)
    #1      JpegScan._decodeHuffman (package:image/src/formats/jpeg/jpeg_scan.dart:134:18)
    #2      JpegScan._decodeACSuccessive (package:image/src/formats/jpeg/jpeg_scan.dart:238:20)
    #3      JpegScan._decodeBlock (package:image/src/formats/jpeg/jpeg_scan.dart:308:13)
    #4      JpegScan.decode (package:image/src/formats/jpeg/jpeg_scan.dart:78:11)
    #5      JpegData._readSOS (package:image/src/formats/jpeg/jpeg_data.dart:568:55)
    #6      JpegData._read (package:image/src/formats/jpeg/jpeg_data.dart:338:11)
    #7      JpegData.read (package:image/src/formats/jpeg/jpeg_data.dart:94:5)
    #8      JpegDecoder.decodeImage (package:image/src/formats/jpeg_decoder.dart:46:10)
    #9      decodeImage (package:image/src/formats/formats.dart:60:18)
    
    

    Here is one such image:

    test

    opened by sanmadjack 33
  • How to support more fonts and sizes?

    How to support more fonts and sizes?

    Thanks for this great lib. You have provided couple fonts with this approach.

    final BitmapFont arial_14 = new BitmapFont.fromZip(_ARIAL_14);
    const List<int> _ARIAL_14 = const [...];
    

    How is this _ARIAL_14 get generated? Is it possible to support Chinese Font?

    opened by EasonPai 24
  • Getting a `NoSuchMethodError: The getter 'exif' was called on null.` when converting a .png to .jpeg

    Getting a `NoSuchMethodError: The getter 'exif' was called on null.` when converting a .png to .jpeg

    This is my code. Image comes directly from the camera using the image_picker plugin:

    var imageFile = await ImagePicker.pickImage(source: ImageSource.camera);
    
    try {
          var pngImage = image.decodePng(imageFile.readAsBytesSync());
          print("## Image decoded fine");
          var jpegFile = new File(path.join(tempPath, 'upload.jpg'));
          print("## 1");
          var jpegBytes = image.encodeJpg(pngImage);
          print("## 1B");
          jpegFile.writeAsBytesSync(jpegBytes);
          print("## 2");
          imageFile = jpegFile;
          print("## 3");
        } catch (error) {
          print("## ERROR");
          print(error);
          print("## ERROR DONE");
        }
    

    And it logs to console:

    I/flutter (15417): ## Camera filename/storage/emulated/0/Android/data/com.scanrapp/files/Pictures/3967201f-c26f-49db-8d04-09929bace1f21282873232.png
    I/flutter (15417): ## Image decoded fine
    I/flutter (15417): ## 1
    I/flutter (15417): ## ERROR
    I/flutter (15417): NoSuchMethodError: The getter 'exif' was called on null.
    I/flutter (15417): Receiver: null
    I/flutter (15417): Tried calling: exif
    I/flutter (15417): ## ERROR DONE
    

    If instead of decodePng I use decodeImage, then it doesn't fail. But the generated image seems invalid, I can't open it with any application.

    opened by pablote 23
  • Progress event?

    Progress event?

    Hi, encoding/decoding images takes a little while (especially on mobile devices). It would be nice to have an optional progress event after each line or so of encoding/decoding. Possible?

    opened by tomsonar 23
  • Adding GPU textureformats

    Adding GPU textureformats

    Not sure this fits this library but: Support various GPU texture formats would be helpful for WebGL applications. ETC, PVRTC, S3TC/DXTC and maybe crunch. Not sure if its possible to write compression/decompression for all these formats in dart because some of them may have no public spec. Maybe it is easier to use binaries here.

    opened by pjako 20
  • Index out of range

    Index out of range

    When I use the encodePng(image) it returns with the error.

    RangeError (index): Index out of range: index should be less than 57088: 57088

    It says that the index should be less than 57088. However, my index is 5088 which is the image size.

    opened by MATTYGILO 19
  • It works, but it is very slow

    It works, but it is very slow

    These comments relate to Flutter as far as this is relevant.

    I am seeing a fair few comments about performance. Sadly, I am seeing the same. Processing a camera roll photo, based on your simple sample, took 45 seconds. The copyResize took about 10 seconds.

    Is this because this is done synchronously or is it just slow?

    Is a shame as it does work.

    opened by fmay 18
  • decodeImage is slow on iOS with large images (Flutter)

    decodeImage is slow on iOS with large images (Flutter)

    Hey there,

    I just implemented your image library with flutter and we are noticing very slow decoding on iOS.

    This is my compression function:

      static Future<File> compressImageFile(File inputFile,
          {int resizePercentage = 50, int quality = 90}) async {
        List<int> bytes = await inputFile.readAsBytes();
    
        Image image = decodeImage(bytes);
    
        if (image.height > 1500 || image.width > 1500) {
          print("Resize required");
          print("Image size before: ${image.height}x${image.width}");
          var newWidth = (image.width / 100 * resizePercentage).toInt();
          var newHeight = (image.height / 100 * resizePercentage).toInt();
    
          Image resizedImage = copyResize(image, newWidth, newHeight);
    
          print("Image size after: ${resizedImage.height}x${resizedImage.width}");
    
          String originalFileName = basename(inputFile.path);
          String filePath = inputFile.parent.path;
          String newFile =
              join(filePath, originalFileName.split('.').first + "_compressed.jpg");
    
          File outputFile = new File(newFile);
          outputFile.writeAsBytesSync(encodeJpg(resizedImage, quality: quality),
              mode: FileMode.WRITE, flush: true);
    
          return outputFile;
        }
    
        return inputFile;
      }
    

    This is the sample image we tried on both Android & iOS. Android takes around 5 seconds for the function to run (most time in "decodeImage") and the app crashed after a few minutes waiting for decodeImage on iOS.

    https://www.pexels.com/photo/1-wtc-america-architecture-buildings-374710/

    opened by btastic 18
  • decodeImage call stuck on real devices

    decodeImage call stuck on real devices

    I am trying to use the library for resizing photos with the following illustrative code. But when i tested on real iphone (iphone 6s, ios 11.4) devices (i tested on two different ones and got the same result), it always got stuck on the function call decodeImage (just won't finish). But it worked fine on an iOS simulator. I tried different sizes of jpg images like a few hundred kilobytes to a few megabytes and got the same behavior.

    Is this a known issue?

     // resize image into constrained dimensions (if necessary)
      static Future<Image> _capImageInFile(File originalImagePath) async {
        logger.fine("start decodeing");
        Image originalImage = decodeImage(await originalImagePath.readAsBytes());
    
        logger.fine(
            "it's a ${originalImage.height}*${originalImage.width} image from ${originalImagePath.path}");
      //...
    }
    
    opened by mylyuic 16
  • Image file decoding function: imageLib.decodeImage is very time consuming.

    Image file decoding function: imageLib.decodeImage is very time consuming.

    I am using this function to decode a picture of about 100k, it takes about 10s-20s (dubug 3s and release >10s) to run on the Android real machine, and it will block the current UI display.

    The debug version consumes about 3 seconds, while the release version consumes more than 10s. code show as below:

    var image =  imageLib.decodeImage(imgfile.readAsBytesSync());
    
    opened by 370966584 15
  • RGB list to Image

    RGB list to Image

    [255, 0, 0, 0, 255, 255, 0, 0, 255, 255, 255, 0, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 255, 0, 0, 0, 255, 255, 255, 255, 0, 0, 255, 0, 0, 0, 255, 0, 255, 0, 0, 0, 0, 0, 255, 0, 255, 255, 0, 255, 255, 255, 255, 255, 255, 255, 0, 255, 255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 0, 255, 0, 0, 0, 255, 0, 0, 255, 255, 0, 0, 0, 0, 0, 0, 255, 0, 255, 255, 0, 255, 0]

    I have the RGB list, how can i convert it to image using ur package?

    opened by shinewanna 0
  • copyResizeCropSquare antialiasing issue with rounded corners

    copyResizeCropSquare antialiasing issue with rounded corners

    Thank you for adding support for rounded corners to all the square-related APIs.

    I'm trying to use use the copyResizeCropSquare to add support for generating round-corners icons (as required by Apple) to the flutter_launcher_icons. Starting off 1024x1024 icon, shrinking it to 824 size and using corner radius between 180..190.

    image = compositeImage(
            Image(
              width: 1024,
              height: 1024,
              numChannels: 4,
              backgroundColor: ColorUint8.rgba(0, 0, 0, 0),
            ),
            copyResizeCropSquare(
              image,
              size: 824,
              radius: 190, // 185.4,
              interpolation:
                  image.width >= 824 ? Interpolation.average : Interpolation.linear,
            ),
            center: true,
          );
    

    The composite image has transparent black background. But I get the same results with transparent white and also without the composite image. The result has some noticeable artifacts on the rounded corners.

    Not sure if I'm missing something about method call parameters or this method need some additional parameter to specify background color for the transparent antialiasing for the corner arc part.

    If it would help, I can try to create a simpler example or a test in the image package.

    You could also take a look at my fork of the flutter_launcher_icons at https://github.com/ekuleshov/flutter_launcher_icons.git use the macos_round_corners branch. Then:

    cd example/flavors
    flutter create .
    flutter pub run flutter_launcher_icons
    

    The generated file is located at example/flavors/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png

    image image
    opened by ekuleshov 7
  • ImageData documentation

    ImageData documentation

    Please add a documentation to ImageData and how the channels in Image are handled. Looking the code it seems that the channels order is always red, green, blue and alpha.

    Also I don't know a use case for an Uint32 channel if ImageData has multiple channels. I use in other projects an Uint32 to represent a 32bit pixels with 4 8bits values in it (like: r,g,b,a).

    opened by gmpassos 12
  • Copying Rotated Rectangles from an Image

    Copying Rotated Rectangles from an Image

    I'm in a similar situation to this question where I want to be able to rotate and transform the bounding box coordinates that copyRectify uses. I'm not so concerned about the structure to hold coordinates, but whether this is even possible: How to Transform Coordinates using a Matrix4

    I took a whack at it using the Image Library and vector_math Library like the code below. Output: I am getting some rotation, but It is the image piece itself along with another portion of the larger image outside of the original bounding box (that's another problem when rotating too much): (top=original image piece, bottom=rotated) https://imgur.com/82WNCP6

    Expected: I want the "bounding box/selection" to be rotated and then the image copied from there. For example, If I applied the rotation transformation to 30 degrees, then the output would be a normal, non-rotated image that has been cropped with rotated sides that look more rhomboid than square like this: https://imgur.com/WKXBKs1

    Question Why is the entire image rotated and not the "bounding box"? Is it even possible to use CopyRectify to copy a piece of an image inside of a rotated rectangle or is my approach wrong?

     // initialize integers for initial points 
     // x2 is width ; y2 is height
     x1=0; y0=y; x2=100; y2=100;
    
    // create 4 points of a rectangle for topLeft to bottomRight
      imglib.Point p1 = imglib.Point(x1, y1);
      imglib.Point p2 = imglib.Point(x2, y1);
      imglib.Point p3 = imglib.Point(x1, y2); 
      imglib.Point p4 = imglib.Point(x2, y2);
    
    // put the 4 points in 4 vectors
      vector_math.Vector3 v1 = vector_math.Vector3(x1.toDouble() , y1.toDouble(), 1);
      vector_math.Vector3 v2 = vector_math.Vector3(x2.toDouble() , y1.toDouble(), 1);
      vector_math.Vector3 v3 = vector_math.Vector3(x1.toDouble() , y2.toDouble(), 1);
      vector_math.Vector3 v4 = vector_math.Vector3(x2.toDouble() , y2.toDouble(), 1);
    
    // Create a matrix4, rotate it and apply it to all 4 points/vectors
     vector_math.Matrix4  T = vector_math.Matrix4.rotationZ(vector_math.radians(45));  
      v1 = T.transform3(v1);
      v2 = T.transform3(v2);
      v3 = T.transform3(v3);
      v4 = T.transform3(v4); 
    
    // pull the new rotated point values out of the vectors: 
      p1.x = v1[0];
      p1.y =v1[1];
      p2.x = v2[0];
      p2.y =v2[1];
      p3.x = v3[0];
      p3.y =v3[1];
      p4.x = v4[0];
      p4.y =v4[1];
    
    // copyRectify the source image with transformed points
    imglib.Image angledSlice = imglib.copyRectify(
            srcImage, 
            topLeft: p1, 
            topRight: p2, 
            bottomLeft: p3, 
            bottomRight: p4,
             );
    
    opened by cdigit 2
  • decodePng returns empty buffer

    decodePng returns empty buffer

    The decodePng used to work nicely with my PNG file in previous versions of Flutter. ByteData bytes = await rootBundle.load('images/pestscope_tm.png'); logoImage = image.decodePng(bytes.buffer.asUint8List()); Suddenly it decodes PNG file, the size is set, and some other data too, but buffer is full of zeros: Image blendMethod: BlendMode (BlendMode.over) channels: Channels (Channels.rgba) data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... disposeMethod: DisposeMode (DisposeMode.clear) duration: 0 exif: ExifData height: 82 iccProfile: ICCProfileData textData: null width: 480 xOffset: 0 yOffset: 0 hashCode: 780885460 length: 39360 numberOfChannels: 4 runtimeType: Type (Image) I tried different methods and still getting zeros.

    opened by Mmisiek 15
Owner
Brendan Duncan
Senior software engineer at Unity. Past: Apple, Google, PDI/DreamWorks Animation, Disney Animation Studios.
Brendan Duncan
A library for parsing and encoding IEEE-754 binary floating point numbers.

Dart IEEE754 library This library provides decoding and transforming IEEE754 floating point numbers in binary format, double format, or as exponent an

null 0 Dec 24, 2021
A dynamic, Stream-based API for job scheduling in Dart, capable of processing on different triggers.

Pendulum A library for task-scheduling in Dart. Exports a Task class that returns Streams, with a number of versatile options to customize how Tasks a

Aditya Kishore 1 Aug 22, 2020
Plist parser - A Plist parser for Flutter supports XML and binary Apple Property list (plist) formats

Plist Parser for Flutter ?? A Flutter Plugin for Plist parser supporting XML and

dirablue ( gaku ) 4 Nov 17, 2022
Custom style-dictionary transforms and formats to generate Flutter resources from a Figma Design Token plugin export..

style-dictionary-figma-flutter An extension to style-dictionary to support more custom types with Flutter as target platform. It supports the custom t

Aloïs Deniel 24 Dec 30, 2022
Zooper flutter encoding utf16 - Helper classes to encode and decode UTF16 string to List

zooper_flutter_encoding_utf16 Helper classes to encode and decode UTF16 string t

Zooper 0 Feb 10, 2022
Flutter simple image crop - A simple and easy to use flutter plugin to crop image on iOS and Android

Image Zoom and Cropping plugin for Flutter A simple and easy used flutter plugin to crop image on iOS and Android. Installation Add simple_image_crop

null 97 Dec 14, 2021
This library provides the easiest and powerful Dart/Flutter library for Mastodon API 🎯

The Easiest and Powerful Dart/Flutter Library for Mastodon API ?? 1. Guide ?? 1.1. Features ?? 1.2. Getting Started ⚡ 1.2.1. Install Library 1.2.2. Im

Mastodon.dart 55 Jul 27, 2023
Album Image is based in photo_manager package and has the same concept as image_picker but with a more attractive interface to choose an image or video from the device gallery, whether it is Android or iOS

Album Image is based in photo_manager package and has the same concept as image_picker but with a more attractive interface to choose an image or vide

Phuong Vu 2 Oct 13, 2022
A middleware library for Dart's http library.

http_middleware A middleware library for Dart http library. Getting Started http_middleware is a module that lets you build middleware for Dart's http

TED Consulting 38 Oct 23, 2021
Flutter plugin for selecting images from the Android and iOS image library, taking new pictures with the camera, and edit them before using such as rotation, cropping, adding sticker/text/filters.

advance_image_picker Flutter plugin for selecting multiple images from the Android and iOS image library, taking new pictures with the camera, and edi

Weta Vietnam 91 Dec 19, 2022
Form builder image picker - Form builder image picker for flutter

form_builder_image_picker Field for picking image(s) from Gallery or Camera for

Ferri Sutanto 0 Jan 28, 2022
Flutter Image add drag sort, Image add drag sort, support click event, delete, add, long press drag sort.

flutter_image_add_drag_sort Flutter Image add drag sort, Image add drag sort, support click event, delete, add, long press drag sort, support video fi

null 5 Jun 23, 2020
In this repo you will see how to pick images from the image library and also, see how to store the selected images on Firebase.

flutterimageapp Flutter Tutorial - Upload Images using Firebase Storage. Flutter Tutorial - Upload Images using Firebase Storage Video series can be w

Whatsupcoders 60 Nov 4, 2022
A powerful plugin that fully uses the native image library's ability to display images on the flutter side.

PowerImage A powerful plugin that fully uses the native image library's ability to display images on the flutter side. 中文文档 Features: Supports the abi

Alibaba 422 Dec 23, 2022
Flutter Control is complex library to maintain App and State management. Library merges multiple functionality under one hood. This approach helps to tidily bound separated logic into complex solution.

Flutter Control is complex library to maintain App and State management. Library merges multiple functionality under one hood. This approach helps to

Roman Hornak 23 Feb 23, 2022
Flutter book library - Book Library Application with Flutter and Google Book API

Book Library Application Flutter iOS, Android and Web with Google Book API Demo

Nur Ahmad H 0 Jan 25, 2022
Dart web3 - A dart library that connects and interacts with the Ethereum blockchain

dart_web3 A dart library that connects and interact with the Ethereum blockchain

p2bh 9 Sep 13, 2022