This is a reproduction project (relevant code is also below). I want to convert a Vec
use image::ImageFormat;
fn main() {
{
let pixels = image::open("test_image_png.png").unwrap().raw_pixels();
let converted = image::load_from_memory(&pixels).unwrap();
let converted_with_format = image::load_from_memory_with_format(&pixels, ImageFormat::Png).unwrap();
}
{
let pixels = image::open("test_image_jpg.jpg").unwrap().raw_pixels();
let converted = image::load_from_memory(&pixels).unwrap();
let converted_with_format = image::load_from_memory_with_format(&pixels, ImageFormat::Jpeg).unwrap();
}
}
'pixels' are is a vector of raw pixel data.
I believe load_from_memory_with_format(&pixels, ImageFormat::Png) is attempting to read the byte array as if it were a PNG image (e.g. something that starts with a PNG header and contains PNG image data. Not raw pixels.)
'pixels' also doesn't contain any information about the width/height of the image or what the pixel format is RGB, RGBA, etc. So the exact number of pixels is not known because the size in bytes of each pixel is not known, and if you did know how many pixels the byte vector represented, you still wouldn't know the width/height of the image. For example, an image can be 100x100 pixels or 50x200 pixels can contain the same amount of pixels.
@pix64 ok, so I need to call an other method. The pixels method was called because I saw it returns a Vec
Do you know a method I can call to transform a Vec to an image?
I think ImageBuffer::from_raw(width, height, pixels) is what you are looking for.
@fintelia the rust compiler want me to assign it an explicit type, I don't know which one to use, I just want to convert bytes to an image.
Just use whatever type your image is. If it's RGB, you can use let converted: ImageBuffer<Rgb<u8>, _> = ImageBuffer::from_raw(weight, height, pixels).unwrap();, or since you're just converted from a Vec it's as simple as let converted = RgbImage::from_raw(width, height, pixels).unwrap();. There are types for Gray, RGBA, etc., too.
@aschampion Thanks, I think I got it working now :)