Search code examples
rustpnghttpresponseqr-codeactix-web

How do I get from an image::ImageBuffer to a actix_web::HttpResponse


The goal is to generate a qr-code using the crate qrcode and send it immediately as a png file for download using actix-web

So far I have:

let qr = QrCode::new(&format!("http://example.com/{}", &link_id)).unwrap();
let png: ImageBuffer<Luma<u8>, Vec<u8>> = qr.render::<Luma<u8>>().build();

Which contains the qrcode. I can save this to a file using it's .save() method. But ideally I would not take that overhead and instead send the file immediately. However I fail to pass correct data to actix-web.

I tried the following which compiles but does send only a faulty image that cannot be viewed:

HttpResponse::Ok()
                .set(ContentType::png())
                .body(Bytes::from(png.into_raw()))

Solution

  • Like so:

        let qr = QrCode::new("http://example.com/xyz").unwrap();
        let png: ImageBuffer<Luma<u8>, Vec<u8>> = qr.render::<Luma<u8>>().build();
        let mut w = Cursor::new(Vec::new());
        DynamicImage::ImageLuma8(png)
            .write_to(&mut w, ImageOutputFormat::Png)
            .unwrap();
        let vec = w.into_inner();
        // vec now contains the PNG bytes