image-rs / imageproc

Image processing operations
MIT License
758 stars 149 forks source link

how encode drawed image to [u8] ? #668

Closed SudoDios closed 5 months ago

theotherphil commented 5 months ago

The Image<P> type in this library is an alias for ImageBuffer<P, Vec<P::Subpixel>>. This means that for RGB, RGBA and Luma images the into_raw() function will return a Vec<u8>: https://docs.rs/image/latest/image/struct.ImageBuffer.html#method.into_raw

SudoDios commented 5 months ago

I used into_raw(),but this is not for an encoded format. Basically, my question is to return the encoded (like jpeg) buffer to me instead of saving it in a file.

SudoDios commented 5 months ago

I did a search in the save function and finally it reached encoders. But encoders only write to std write not on Vec

ripytide commented 5 months ago

imageproc returns images in pixel form which is a simple 2D-array of pixels. Jpeg is a compressed file-format which requires jpeg-codec encoding. This is implemented in the image crate. If you have an Image type as returned by many of the image processing functions in this crate then you can do this to convert it into a jpeg:

let mut buffer = Vec::new();
image.write_to(&mut buffer, ImageFormat::Jpeg).expect("jpeg failed to encode");

The buffer vec can now be used as &[u8] of an encoded jpeg.

SudoDios commented 5 months ago

Thank you for your answer 🌹. I will take a test and close the issue.

SudoDios commented 5 months ago

function write_to works perfect. but vector is not seekable and i used std::io::Cursor:

let mut buffer: Cursor<Vec<u8>> = Cursor::new(Vec::new());
image.write_to(&mut buffer, ImageFormat::Jpeg).expect("jpeg failed to encode");