Skip to content

Creating GIF from JPEG frames? #44

Open
@captainviet

Description

@captainviet

Hi,

I'm new to Rust, yet I need to write a piece of Rust code to create a GIF file from a series of JPEG screenshots.

Currently my generated GIF is glitchy, the content seems enlarged and the colors don't look right.
I'm wondering whether this is related to the compatibility of JPEG as frames for GIF, or because I'm using the wrong palette for the GIF Encoder? I'm learning so comments are welcome! Thanks in advance!

A brief summary for the code below:

  • screenshot() returns an image::RgbaImage
  • the width and height of each of the image (and the derived Frame) is fixed
  • the color_map is set to [ FF, FF, FF, FF, 00, 00 ] (which I supposed is R, G, B, and A enabled? Pardon me as I cannot find any reference to the palette parameter)
  • the individual JPEG images are correctly generated
  • the GIF is created with frames derived from the JPEG images
extern crate image;
extern crate time;
extern crate gif;
extern crate screenshot;

use image as im;
use std::fs::File;
use std::thread;
use std::time::Duration;
use time::PreciseTime as tpt;
use gif::{Frame, Encoder, Repeat, SetParameter};
use std::borrow::Cow;
use screenshot::screenshot;

fn main() {
    let mut image = File::create("sample.gif").unwrap();
    let img: im::RgbaImage = screenshot();
    println!("Len: {}", img.len());
    println!("Original: {}x{}", img.width(), img.height());
    let width: u16 = img.width() as u16;
    let height: u16 = img.height() as u16;
    println!("Compressed: {}x{}", width, height);
    let color_map = &[0xFF, 0xFF, 0xFF, 0xFF, 0, 0];
    let mut encoder = Encoder::new(&mut image, width, height, color_map).unwrap();
    encoder.set(Repeat::Infinite).unwrap();
    for i in 0..6 {
        let start = tpt::now();
        let img: im::RgbaImage = screenshot();
        let mid1 = tpt::now();
        println!("Getting raw buffer...");
        let pixes: &mut [u8] = &mut img.into_raw();
        println!("Getting frame...");
        //let mut frame = Frame::from_rgba(width, height, pixes);
        let mut frame = Frame::default();
        frame.width = width;
        frame.height = height;
        frame.buffer = Cow::Borrowed(pixes);
        println!("Writing frame...");
        encoder.write_frame(&frame).unwrap();
        let end = tpt::now();
        println!("Duration: {} {}", start.to(mid1).num_milliseconds(), mid1.to(end).num_milliseconds());
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions