Curl-rust send ImageBuffer

i'm trying to send ImageBuffer that come from this library via curl-rust, in curl-rust there is send buffer option.

i don't know why, but my server receive invalid image file, here;s my current code :

extern crate camera_capture;
extern crate image;

// use std::fs::File;
// use std::path::Path;
use curl::easy::{Easy, Form};

fn main() {
    let cam = camera_capture::create(0).unwrap();

    let mut cam_iter = cam.fps(5.0).unwrap().start().unwrap();
    let img = cam_iter.next().unwrap();

    // let file_name = "test.png";
    // let path = Path::new(&file_name);
    // let _ = &mut File::create(&path).unwrap();
    // img.save(&path).unwrap();

    // println!("img saved to {}", file_name);
    println!("sending image...");

    let mut easy = Easy::new();
    easy.url("http://localhost/upload").unwrap();
    easy.post(true).unwrap();

    let mut form = Form::new();
    form.part("image").buffer("image.jpg", img.into_vec()).add().unwrap();
    easy.httppost(form).unwrap();

    easy.perform().unwrap();

    println!("{}", easy.response_code().unwrap());
}

the form buffer can receive img.into_vec() or img.into_raw() but both are sending invalid file.

You're sending raw image data. You need to encode it as a jpg first; something like

let mut buffer = Vec::new();
image::jpeg::JPEGEncoder(&mut buffer)
    .encode(
        img,
        img.width(),
        img.height(),
        <image::Rgb<u8> as image::Pixel>::color_type(),
    )
    .unwrap();

// ...

form.part("image").buffer("image.jpg", buffer).add().unwrap();
1 Like

but img.save(&reader).unwrap(); save a valid image file (as .png). and i already try to change uploaded file format and it's still invalid to open

When you saved the image to a file, what did you pass to the buffer call? Did you read the file into memory? What is &reader?

ups, &reader should be &path

    // let file_name = "test.png";
    // let path = Path::new(&file_name);
    // let _ = &mut File::create(&path).unwrap();
    // img.save(&path).unwrap();

Saving the image to a file doesn't change img, though. Did you read from &file_name into a Vec<u8> after you wrote the file?

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.