1#![warn(missing_docs)]
2
3use std::io::Cursor;
7use std::path::Path;
8
9use anyhow::anyhow;
10use id3::TagLike;
11use image::DynamicImage;
12
13pub fn embed_image(music_filename: &Path, image_filename: &Path) -> anyhow::Result<()> {
20 let image = image::open(&image_filename)
21 .map_err(|e| anyhow!("Error reading image {:?}: {}", image_filename, e))?;
22
23 embed_image_from_memory(music_filename, &image)
24}
25
26pub fn embed_image_from_memory(
33 music_filename: &Path,
34 image: &image::DynamicImage,
35) -> anyhow::Result<()> {
36 let mut tag = read_tag(music_filename)?;
37
38 let mut encoded_image_bytes = Cursor::new(Vec::new());
39 image
41 .write_to(&mut encoded_image_bytes, image::ImageOutputFormat::Jpeg(90))
42 .unwrap();
43
44 tag.add_frame(id3::frame::Picture {
45 mime_type: "image/jpeg".to_string(),
46 picture_type: id3::frame::PictureType::CoverFront,
47 description: String::new(),
48 data: encoded_image_bytes.into_inner(),
49 });
50
51 tag.write_to_path(music_filename, id3::Version::Id3v23)
52 .map_err(|e| {
53 anyhow!(
54 "Error writing image to music file {:?}: {}",
55 music_filename,
56 e
57 )
58 })?;
59
60 Ok(())
61}
62
63pub fn extract_first_image(music_filename: &Path, image_filename: &Path) -> anyhow::Result<()> {
70 extract_first_image_as_img(music_filename)?
71 .save(&image_filename)
72 .map_err(|e| anyhow!("Couldn't write image file {:?}: {}", image_filename, e))
73}
74
75pub fn extract_first_image_as_img(music_filename: &Path) -> anyhow::Result<DynamicImage> {
81 let tag = read_tag(music_filename)?;
82 let first_picture = tag.pictures().next();
83
84 if let Some(p) = first_picture {
85 image::load_from_memory(&p.data).map_err(|e| anyhow!("Couldn't load image: {}", e))
86 } else {
87 Err(anyhow!("No image found in music file"))
88 }
89}
90
91pub fn remove_images(music_filename: &Path) -> anyhow::Result<()> {
97 let mut tag = read_tag(music_filename)?;
98 tag.remove("APIC");
99
100 tag.write_to_path(music_filename, id3::Version::Id3v23)
101 .map_err(|e| anyhow!("Error updating music file {:?}: {}", music_filename, e))?;
102
103 Ok(())
104}
105
106fn read_tag(path: &Path) -> anyhow::Result<id3::Tag> {
107 id3::Tag::read_from_path(&path).or_else(|e| {
108 eprintln!(
109 "Warning: file metadata is corrupted, trying to read partial tag: {}",
110 path.display()
111 );
112 e.partial_tag
113 .clone()
114 .ok_or_else(|| anyhow!("Error reading music file {:?}: {}", path, e))
115 })
116}