Convert image data from Vec<u8> to Image<&[u8]> for turbojpeg

I'm rather new to Rust and playing around with resizing images using turbojpeg, since it's rather quick.

This is basically what I'm doing:

    //read jpeg from disc
    let jpeg_data = std::fs::read(img_path_in).unwrap();
    //decompress jpeg image data as Image<Vec<u8>>
    let img = turbojpeg::decompress(&jpeg_data,turbojpeg::PixelFormat::RGB).unwrap();
    //convert image data to be able to resize image
    let img_to_resize = img.as_deref().pixels;
    ...resize image....
    //compress the image data as jpeg
    let jpeg_data_out = turbojpeg::compress(img_resized, 75, turbojpeg::Subsamp::Sub2x2).unwrap();
    //save jpeg to file
    std::fs::write(img_path_out, jpeg_data_out).unwrap();

I have been using the resize create to try and resize the image data, which seem to work, but how do I go about converting the resized image data, which is of type Vec<u8>, to Image<&[u8]> that turbojpeg::compress() accepts?

I might be doing something fundamentally wrong here, and therefor asking the wrong question so feel free to contribute to solving the problem instead of answering my question.

You can construct an Image directly. Most of the fields should be fairly obvious, but you may have to experiment a bit to get pitch right.

I haven't used these libraries, but I would look at image::ImageBuffer::from_raw(), it says it can take a Vec as the input.

Yes, I was just trying that but still some problems with wrong type:

let img_resized = turbojpeg::Image {
   pixels: dst,
   width: 320, 
   pitch: 320 * turbojpeg::PixelFormat::RGB.size() * 2,
   height: 240,
   format: turbojpeg::PixelFormat::RGB

But then I get expected struct Image<&[u8]>, found struct Image<Vec<u8>>
How do I go from my <&Vec<u8>> to <&[u8]>?

dst.as_slice() should work

That worked but now I get:

error[E0658]: use of unstable library feature 'slice_pattern': stopgap trait for slice patterns
use core::slice::SlicePattern;

You may have accidentally imported the unstable SlicePattern trait as a code completion for as_slice. Just delete the import of the trait, there's an inherent as_slice method on Vec and that's the one you want.

1 Like

Ha, that was funny. It would have taken me a while to figure that one out.
After removing use core::slice::SlicePattern; it works, thank you.
(It doesn't really work but it compiles so I can fix the rest)

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.