-
-
Notifications
You must be signed in to change notification settings - Fork 272
Examples
Brendan Duncan edited this page May 16, 2019
·
39 revisions
Load a jpeg, resize it, and save it as a png
import 'dart:io';
import 'package:image/image.dart';
void main() {
// Read a jpeg image from file.
Image image = decodeImage(File('test.jpg').readAsBytesSync());
// Resize the image to a 120x? thumbnail (maintaining the aspect ratio).
Image thumbnail = copyResize(image, width: 120);
// Save the thumbnail as a PNG.
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 = 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 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 Image.fromBytes(canvas.width, canvas.height, imageData.data,
format: Format.rgba);
}
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(format: Format.rgba));
// 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';
import 'package:image/image.dart';
void main() {
// Create an image
Image image = 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
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: Channel.luminance);
}
Save the frames from a WebP animation to PNG files
import 'dart:io';
import 'package:image/image.dart';
void main() {
List<int> bytes = File('BladeRunner.webp').readAsBytesSync();
Animation anim = decodeWebPAnimation(bytes);
for (int i = 0; i < anim.numFrames; ++i) {
AnimationFrame frame = anim[i];
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';
import 'package:image/image.dart';
void main(List<String> argv) {
String path = argv[0];
Directory dir = Directory(path);
List files = dir.listSync();
List<int> trimRect;
for (var f in files) {
if (f is! File) {
continue;
}
List<int> bytes = f.readBytesSync();
Image image = decodeImage(bytes);
if (image == null) {
continue;
}
if (trimRect == null) {
trimRect = findTrim(image, mode: TrimMode.transparent);
}
Image trimmed = copyCrop(image, trimRect[0], trimRect[1],
trimRect[2], trimRect[3]);
String name = f.path.split(RegExp(r'(/|\\)')).last;
File('$path/trimmed-$name').writeBytesSync(encodeNamedImage(image, f.path));
}
}
Load and process an image in a separate isolate thread
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 decode(DecodeParam param) {
// Read an image from file (webp in this case).
// decodeImage will identify the format of the image and use the appropriate
// decoder.
Image image = decodeImage(param.file.readAsBytesSync());
// Resize the image to a 120x? thumbnail (maintaining the aspect ratio).
Image thumbnail = gaussianBlur(copyResize(image, width: 120), 5);
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 {
ReceivePort receivePort = ReceivePort();
await Isolate.spawn(decode,
DecodeParam(File('test.webp'), receivePort.sendPort));
// Get the processed image from the isolate.
Image image = await receivePort.first;
File('thumbnail.png').writeAsBytesSync(encodePng(image));
}