Skip to content
William edited this page May 8, 2018 · 39 revisions

Load a jpeg, resize it, and save it as a png

    import 'dart:io' as Io;
    import 'package:image/image.dart';
    void main() {
      // Read a jpeg image from file.
      Image image = decodeImage(new Io.File('test.jpg').readAsBytesSync());

      // Resize the image to a 120x? thumbnail (maintaining the aspect ratio).
      Image thumbnail = copyResize(image, 120);
    
      // Save the thumbnail as a PNG.
      new Io.File('out/thumbnail-test.png')
            ..writeAsBytesSync(encodePng(thumbnail));
    }

Convert all WebP images on a page to PNG so that browsers lacking WebP can view them

    import 'dart:html' as Html;
    import 'package:crypto/crypto.dart';
    import 'package:image/image.dart';

    void main() {
      var images = Html.querySelectorAll('img');

      for (var img in images) {
        if (img.src.toLowerCase().endsWith('.webp')) {
          // Since the browser might not have decoded the image, use an HttpRequest to get the image
          // data, convert it to binary, decode the WebP using the image library, re-encode it to
          // PNG, base64 encode the PNG, and replace the img src with a data URL.
          var req = new Html.HttpRequest();
          req.open('GET', img.src);
          req.overrideMimeType('text\/plain; charset=x-user-defined');
          req.onLoadEnd.listen((e) {
            if (req.status == 200) {
              // convert the responseText to a byte list.
              var bytes = req.responseText.split('').map((e){
                return new String.fromCharCode(e.codeUnitAt(0) & 0xff);
              }).join('').codeUnits;

              var image = decodeImage(bytes);
              var png = encodePng(image);

              var png64 = CryptoUtils.bytesToBase64(png);
              img.src = 'data:image/png;base64,${png64}';
            }
          });
          req.send('');
        }
      }
    }

Read an Image from a Canvas element

    import 'dart:html' as Html;
    import 'package:image/image.dart';

    // Read a Canvas into an Image.
    // The returned Image will be accessing the data of the canvas directly, so any changes you
    // make to the pixels of Image will apply to the canvas.
    Image getImageFromCanvas(Html.CanvasElement canvas) {
      var imageData = canvas.context2D.getImageData(0, 0, canvas.width, canvas.height);
      return new Image.fromBytes(canvas.width, canvas.height, imageData.data);
    }

Write an Image to a Canvas element

    import 'dart:html' as Html;
    import 'package:image/image.dart';

    // Draw an Image onto a Canvas by getting writing the bytes to ImageData that can be
    // copied to the Canvas.
    void drawImageOntoCanvas(Html.CanvasElement canvas, Image image) {
      var imageData = canvas.context2D.createImageData(image.width, image.height);
      imageData.data.setRange(0, imageData.data.length, image.getBytes());
      // Draw the buffer onto the canvas.
      canvas.context2D.putImageData(imageData, 0, 0);
    }

Create an image, draw some text, save it as a png

    import 'dart:io' as Io;
    import 'package:image/image.dart';
    void main() {
      // Create an image
      Image image = new Image(320, 240);
      
      // Fill it with a solid color (blue)
      fill(image, getColor(0, 0, 255));
      
      // Draw some text using 24pt arial font
      drawString(image, arial_24, 0, 0, 'Hello World');
      
      // Draw a line
      drawLine(image, 0, 0, 320, 240, getColor(255, 0, 0), thickness: 3);
      
      // Blur the image
      gaussianBlur(image, 10);
      
      // Generate a PNG
      List<int> png = encodePng(image);
      
      // Save it to disk
      new Io.File('test.png')
            ..writeAsBytesSync(png);
    }

Map the grayscale of the image to its alpha channel

    Image grayscaleAlpha(Image image) {
        // Make sure the image is in RGBA format.
        image.format = Image.RGBA;
        // Map the LUMINANCE (grayscale) of the image to the alpha channel.
        return remapColors(image, alpha: LUMINANCE);
    }

Save the frames from a WebP animation to PNG files

    import 'dart:io' as Io;
    import 'package:image/image.dart';
    void main() {
      List<int> bytes = new Io.File('BladeRunner.webp').readAsBytesSync();
      Animation anim = decodeWebPAnimation(bytes);
      for (int i = 0; i < anim.numFrames; ++i) {
        AnimationFrame frame = anim[i];
        new Io.File('BladeRunner_$i.png')
              ..writeAsBytesSync(encodePng(frame.image));
      }
    }

Load a directory of images, auto-trim the first image, and apply the trim to all subsequent images.

    import 'dart:io' as Io;
    import 'package:image/image.dart';
    void main(List<String> argv) {
      String path = argv[0];
      Io.Directory dir = new Io.Directory(path);
      List files = dir.listSync();
      List<int> trimRect;
      for (var f in files) {
        if (f is! Io.File) {
          continue;
        }
        List<int> bytes = f.readBytesSync();
        Image image = decodeImage(bytes);
        if (image == null) {
          continue;
        }
        if (trimRect == null) {
          trimRect = findTrim(image, mode: TRIM_TRANSPARENT);
        }
        Image trimmed = copyCrop(image, trimRect[0], trimRect[1], trimRect[2], trimRect[3]);
        String name = f.path.split(new RegExp(r'(/|\\)')).last;
        new Io.File('$path/trimmed-$name').writeBytesSync(encodeNamedImage(image, f.path));
      }
    }
Clone this wiki locally