24 releases

0.13.1 Jan 23, 2024
0.12.0 Nov 17, 2022
0.11.4 Jun 27, 2022
0.11.3 Oct 14, 2021
0.5.0 Jun 5, 2015

#9 in Images

Download history 187686/week @ 2024-01-26 207084/week @ 2024-02-02 238046/week @ 2024-02-09 200138/week @ 2024-02-16 245876/week @ 2024-02-23 233112/week @ 2024-03-01 238967/week @ 2024-03-08 237099/week @ 2024-03-15 250257/week @ 2024-03-22 256137/week @ 2024-03-29 204746/week @ 2024-04-05 227653/week @ 2024-04-12 230106/week @ 2024-04-19 228349/week @ 2024-04-26 222969/week @ 2024-05-03 178578/week @ 2024-05-10

898,170 downloads per month
Used in 2,012 crates (70 directly)

MIT/Apache

105KB
2K SLoC

GIF en- and decoding library Build Status

GIF en- and decoder written in Rust (API Documentation).

GIF encoding and decoding library

This library provides all functions necessary to de- and encode GIF files.

High level interface

The high level interface consists of the two types Encoder and Decoder.

Decoding GIF files

// Open the file
use std::fs::File;
let input = File::open("tests/samples/sample_1.gif").unwrap();
// Configure the decoder such that it will expand the image to RGBA.
let mut options = gif::DecodeOptions::new();
options.set_color_output(gif::ColorOutput::RGBA);
// Read the file header
let mut decoder = options.read_info(input).unwrap();
while let Some(frame) = decoder.read_next_frame().unwrap() {
    // Process every frame
}

Encoding GIF files

The encoder can be used to save simple computer generated images:

use gif::{Frame, Encoder, Repeat};
use std::fs::File;
use std::borrow::Cow;

let color_map = &[0xFF, 0xFF, 0xFF, 0, 0, 0];
let (width, height) = (6, 6);
let beacon_states = [[
    0, 0, 0, 0, 0, 0,
    0, 1, 1, 0, 0, 0,
    0, 1, 1, 0, 0, 0,
    0, 0, 0, 1, 1, 0,
    0, 0, 0, 1, 1, 0,
    0, 0, 0, 0, 0, 0,
], [
    0, 0, 0, 0, 0, 0,
    0, 1, 1, 0, 0, 0,
    0, 1, 0, 0, 0, 0,
    0, 0, 0, 0, 1, 0,
    0, 0, 0, 1, 1, 0,
    0, 0, 0, 0, 0, 0,
]];
let mut image = File::create("target/beacon.gif").unwrap();
let mut encoder = Encoder::new(&mut image, width, height, color_map).unwrap();
encoder.set_repeat(Repeat::Infinite).unwrap();
for state in &beacon_states {
    let mut frame = Frame::default();
    frame.width = width;
    frame.height = height;
    frame.buffer = Cow::Borrowed(&*state);
    encoder.write_frame(&frame).unwrap();
}

Frame::from_* can be used to convert a true color image to a paletted image with a maximum of 256 colors:

use std::fs::File;

// Get pixel data from some source
let mut pixels: Vec<u8> = vec![0; 30_000];
// Create frame from data
let frame = gif::Frame::from_rgb(100, 100, &mut *pixels);
// Create encoder
let mut image = File::create("target/indexed_color.gif").unwrap();
let mut encoder = gif::Encoder::new(&mut image, frame.width, frame.height, &[]).unwrap();
// Write frame to file
encoder.write_frame(&frame).unwrap();

Dependencies

~130KB