README.md
1# GIF en- and decoding library [![Build Status](https://travis-ci.org/image-rs/image-gif.svg?branch=master)](https://travis-ci.org/image-rs/image-gif)
2
3GIF en- and decoder written in Rust ([API Documentation](https://docs.rs/gif/)).
4
5# GIF encoding and decoding library
6
7This library provides all functions necessary to de- and encode GIF files.
8
9## High level interface
10
11The high level interface consists of the two types
12[`Encoder`](https://docs.rs/gif/0.10.1/gif/struct.Encoder.html) and [`Decoder`](https://docs.rs/gif/0.10.1/gif/struct.Decoder.html).
13They as builders for the actual en- and decoders and can be used to set various
14options beforehand.
15
16### Decoding GIF files
17
18```rust
19// Open the file
20use std::fs::File;
21use gif::SetParameter;
22let mut decoder = gif::Decoder::new(File::open("tests/samples/sample_1.gif").unwrap());
23// Configure the decoder such that it will expand the image to RGBA.
24decoder.set(gif::ColorOutput::RGBA);
25// Read the file header
26let mut decoder = decoder.read_info().unwrap();
27while let Some(frame) = decoder.read_next_frame().unwrap() {
28 // Process every frame
29}
30```
31
32### Encoding GIF files
33
34The encoder can be used so save simple computer generated images:
35
36```rust
37use gif::{Frame, Encoder, Repeat, SetParameter};
38use std::fs::File;
39use std::borrow::Cow;
40
41let color_map = &[0xFF, 0xFF, 0xFF, 0, 0, 0];
42let (width, height) = (6, 6);
43let beacon_states = [[
44 0, 0, 0, 0, 0, 0,
45 0, 1, 1, 0, 0, 0,
46 0, 1, 1, 0, 0, 0,
47 0, 0, 0, 1, 1, 0,
48 0, 0, 0, 1, 1, 0,
49 0, 0, 0, 0, 0, 0,
50], [
51 0, 0, 0, 0, 0, 0,
52 0, 1, 1, 0, 0, 0,
53 0, 1, 0, 0, 0, 0,
54 0, 0, 0, 0, 1, 0,
55 0, 0, 0, 1, 1, 0,
56 0, 0, 0, 0, 0, 0,
57]];
58let mut image = File::create("target/beacon.gif").unwrap();
59let mut encoder = Encoder::new(&mut image, width, height, color_map).unwrap();
60encoder.set(Repeat::Infinite).unwrap();
61for state in &beacon_states {
62 let mut frame = Frame::default();
63 frame.width = width;
64 frame.height = height;
65 frame.buffer = Cow::Borrowed(&*state);
66 encoder.write_frame(&frame).unwrap();
67}
68```
69
70[`Frame::from_*`](https://docs.rs/gif/0.10.1/gif/struct.Frame.html) can be used to convert a true color image to a paletted
71image with a maximum of 256 colors:
72
73```rust
74use std::fs::File;
75
76// Get pixel data from some source
77let mut pixels: Vec<u8> = vec![0; 30_000];
78// Create frame from data
79let frame = gif::Frame::from_rgb(100, 100, &mut *pixels);
80// Create encoder
81let mut image = File::create("target/indexed_color.gif").unwrap();
82let mut encoder = gif::Encoder::new(&mut image, frame.width, frame.height, &[]).unwrap();
83// Write frame to file
84encoder.write_frame(&frame).unwrap();
85```
86