Can read image from memory

This commit is contained in:
2022-03-22 17:44:13 +01:00
parent 7276236936
commit b94d312a9d
2 changed files with 78 additions and 28 deletions

View File

@ -6,6 +6,7 @@
use std::path::Path;
use anyhow::anyhow;
use image::DynamicImage;
/// Embed the image from `image_filename` into `music_filename`, in-place. Any errors reading ID3
/// tags from the music file or parsing the image get propagated upwards.
@ -14,10 +15,21 @@ use anyhow::anyhow;
/// Tags get written as ID3v2.3.
///
pub fn embed_image(music_filename: &Path, image_filename: &Path) -> anyhow::Result<()> {
let mut tag = read_tag(music_filename)?;
let image = image::open(&image_filename).
map_err(|e| anyhow!("Error reading image {:?}: {}", image_filename, e))?;
embed_image_from_memory(music_filename, &image)
}
/// Embed the image `image` into `music_filename`, in-place. Any errors reading ID3
/// tags from the music file get propagated upwards.
///
/// The image is encoded as a JPEG with a 90% quality setting, and embedded as a "Front cover".
/// Tags get written as ID3v2.3.
///
pub fn embed_image_from_memory(music_filename: &Path, image: &image::DynamicImage) -> anyhow::Result<()> {
let mut tag = read_tag(music_filename)?;
let mut encoded_image_bytes = Vec::new();
// Unwrap: Writing to a Vec should always succeed;
image.write_to(&mut encoded_image_bytes, image::ImageOutputFormat::Jpeg(90)).unwrap();
@ -42,19 +54,23 @@ pub fn embed_image(music_filename: &Path, image_filename: &Path) -> anyhow::Resu
/// there's no embedded images in the mp3 file.
///
pub fn extract_first_image(music_filename: &Path, image_filename: &Path) -> anyhow::Result<()> {
extract_first_image_as_img(music_filename)?
.save(&image_filename).
map_err(|e| anyhow!("Couldn't write image file {:?}: {}", image_filename, e))
}
/// Extract the first found embedded image from `music_filename` and return it as image object
///
/// Any errors from parsing id3 tags will be propagated. The function will also return an error if
/// there's no embedded images in the mp3 file.
///
pub fn extract_first_image_as_img(music_filename: &Path) -> anyhow::Result<DynamicImage> {
let tag = read_tag(music_filename)?;
let first_picture = tag.pictures().next();
if let Some(p) = first_picture {
match image::load_from_memory(&p.data) {
Ok(image) => {
image.save(&image_filename).
map_err(|e| anyhow!("Couldn't write image file {:?}: {}", image_filename, e))?;
},
Err(e) => return Err(anyhow!("Couldn't load image: {}", e)),
};
Ok(())
return image::load_from_memory(&p.data)
.map_err(|e| anyhow!("Couldn't load image: {}", e));
} else {
Err(anyhow!("No image found in music file"))
}