Image to PNG encoded base64 rust

I am currently writing something that gives me an image::RgbImage and I want this image to be encoded into base64.
I've searched a lot but found nothing.

Thanks in advance for helping me!

I found the solution:

let img: image::RgbImage = ...
let img: image::DynamicImage = image::DynamicImage::ImageRgb8(img);

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

You can also use EncoderWriter, which should be a bit more efficient because you don't need to write the whole PNG to an intermediate buffer first:

use base64::{STANDARD, write::EncoderWriter};
use image::{DynamicImage, ImageOutputFormat, ImageResult};

pub fn base64_png(img: DynamicImage) -> ImageResult<Vec<u8>> {
    let mut buf = vec![];
        let mut writer = EncoderWriter::new(&mut buf, STANDARD);
        img.write_to(&mut writer, ImageOutputFormat::Png)?;
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.