crowdagger / epub-builder

A Rust library for generating EPUB files
Mozilla Public License 2.0
135 stars 45 forks source link

Troubles figuring out how to load dummy_image in a real-world scenario #17

Closed angelalonso closed 3 years ago

angelalonso commented 3 years ago

I am trying to add an image to my EPUB by following what's described on README but I cannot seem to pull it off.

let dummy_image = "Not really a PNG image";
(...)
        .add_resource("some_image.png", dummy_image.as_bytes(), "image/png")?

I am miserably failing to figure out the proper way to load the image so that epub_builder can load it into the EPUB. I use calibre's edit book to check the file and it finds the file but it complains that it's "not a valid image".

I tried loading my image with things like: let img = ImageReader::open("images/default-vpc-diagram.png").unwrap();

let img = image::open("images/default-vpc-diagram.png").unwrap();

let filename = "images/default-vpc-diagram.png";
let mut img = File::open(&filename).expect("no file found");                                                                                                                                                 
let metadata = fs::metadata(&filename).expect("unable to read metadata");
let mut buffer = vec![0; metadata.len() as usize];
img.read(&mut buffer).expect("buffer overflow");

let img = fs::read(filename).expect("Unable to read file");

I know for a fact my Rust knowledge is limited (very) and I'm failing to see something obvious. Still it would be great to have a more specific case on how to load those images on the README.

Thanks in advance!

angelalonso commented 3 years ago

I finally solved it! Probably this is obvious to more seasoned Rust developers but I had to walk the trial and error process to make it work (understanding it... that's a different topic).

I was missing this the transformation from Vec to slice: https://stackoverflow.com/questions/42240663/how-to-read-stdioread-from-a-vec-or-slice So, an example of loading an image would go:

let dummy_image = "/path/to/your/image"; let img = fs::read(dummy_image).expect("Unable to read file"); .add_resource("path/at/the/content", img.as_slice(), "image/png")?

I hope someone else finds this useful :)

VirtuousCrane commented 2 years ago

Thank you very much for showing me da wae. I've been stuck trying to add an image for around a week now... Thank you...