Search code examples
image-processingrustbase64

How to convert DynamicImage to Base64?


I can convert a Base64 string to a DynamicImage using the image and base64 crates but I can not convert the image back to a Base64 string.

What I am doing wrong here? How to achieve this?

extern crate base64;
extern crate image;

fn main() {
    /*
    Base64 to image
        let img_buffer = base64::decode("qwerty...").unwrap();
        let mut base_img = image::load_from_memory(img_buffer.as_slice()).unwrap();

    */

    let mut base_img = image::open("player.png").unwrap();

    base_img.invert();

    // base_img.save("player1.png").unwrap();

    // image to Base64
    let res_base64 = base64::encode(base_img.raw_pixels().as_slice());

    println!("{}", res_base64)
}

Base64 value of original image

iVBORw0KGgoAAAANSUhEUgAAAgAAAAIACAYAAAD0eNT6AAAACXBIWXMAAA7EAAAOxAGVKw4bAAAgAElEQVR42uydd5hlRZn/v1Un3dzdt/P0pJ6enANxGKISFEQkg4ur6667uquuCiKCIJKUpAj7U3cN66orWVERVxBmmDxMYHLOM90znfvGk6rq98e9ICoo0Kf73u5+P8+DjPBwZrpO1Xm...

Base64 value of Gimp inverted image

iVBORw0KGgoAAAANSUhEUgAAAgAAAAIACAYAAAD0eNT6AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAB3RJTUUH4wgMCCwxQF4N2QAAIABJREFUeNrsvXmc3FWZ7...

The response I am getting not the proper Base64 value:

////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///...

Solution

  • The Base64 values of the original and Gimp images represent PNG-encoded images. The response you're getting represents raw pixel data. You will need to convert the data to PNG before encoding as Base64. This should do it:

    let mut buf = vec![[]];
    base_img.write_to(&mut buf, image::ImageOutputFormat::PNG);
    let res_base64 = base64::encode(&buf);