Skip to main content

skia_safe/
encode_.rs

1//! Encoding of images into the supported [`EncodedImageFormat`]s.
2
3use crate::{Bitmap, EncodedImageFormat, Pixmap};
4
5#[cfg(feature = "jpeg")]
6pub mod jpeg_encoder;
7pub mod png_encoder;
8// TODO: May support with an optional feature, gn flag `skia_use_rust_png_encode`.
9// pub mod png_rust_encoder;
10#[cfg(feature = "webp-encode")]
11pub mod webp_encoder;
12
13impl Pixmap<'_> {
14    /// Encodes the pixels of this pixmap into an image in the given format, and returns the encoded
15    /// bytes, or `None` if the format is not supported or the encoding fails.
16    ///
17    /// - `quality` An encoder specific value in the range `0..=100`. `None` selects the default of
18    ///   `100`.
19    pub fn encode(
20        &self,
21        format: EncodedImageFormat,
22        quality: impl Into<Option<u32>>,
23    ) -> Option<Vec<u8>> {
24        crate::encode::pixmap(self, format, quality)
25    }
26}
27
28impl Bitmap {
29    /// Encodes the pixels of this bitmap into an image in the given format, and returns the encoded
30    /// bytes, or `None` if the format is not supported or the encoding fails.
31    ///
32    /// - `quality` An encoder specific value in the range `0..=100`. `None` selects the default of
33    ///   `100`.
34    pub fn encode(
35        &self,
36        format: EncodedImageFormat,
37        quality: impl Into<Option<u32>>,
38    ) -> Option<Vec<u8>> {
39        crate::encode::bitmap(self, format, quality)
40    }
41}
42
43impl crate::Image {
44    /// Encode the image and return the resulting bytes, or `None` if the format is not supported or
45    /// the encoding fails.
46    ///
47    /// - `context` If the image was created as a texture-backed image on a GPU context, that context
48    ///   must be provided so the pixels can be read before being encoded. For raster-backed images,
49    ///   it can be `None`.
50    /// - `quality` An encoder specific value in the range `0..=100`. `None` selects the default of
51    ///   `100`.
52    pub fn encode<'a>(
53        &self,
54        context: impl Into<Option<&'a mut crate::gpu::DirectContext>>,
55        format: EncodedImageFormat,
56        quality: impl Into<Option<u32>>,
57    ) -> Option<crate::Data> {
58        crate::encode::image(context, self, format, quality)
59    }
60}
61
62pub mod encode {
63    //! Free functions to encode images into bytes, dispatching to the appropriate encoder
64    //! (JPEG, PNG, WebP) based on the requested [`crate::EncodedImageFormat`].
65
66    #[cfg(feature = "jpeg")]
67    use super::jpeg_encoder;
68    use super::png_encoder;
69    use crate::{Bitmap, EncodedImageFormat, Pixmap};
70
71    pub fn pixmap(
72        bitmap: &Pixmap,
73        format: EncodedImageFormat,
74        quality: impl Into<Option<u32>>,
75    ) -> Option<Vec<u8>> {
76        let mut data = Vec::new();
77        let quality = quality.into().unwrap_or(100).clamp(0, 100);
78        let _ = quality;
79        match format {
80            #[cfg(feature = "jpeg")]
81            EncodedImageFormat::JPEG => {
82                let opts = jpeg_encoder::Options {
83                    quality,
84                    ..jpeg_encoder::Options::default()
85                };
86                jpeg_encoder::encode(bitmap, &mut data, &opts)
87            }
88            EncodedImageFormat::PNG => {
89                let opts = png_encoder::Options::default();
90                png_encoder::encode(bitmap, &mut data, &opts)
91            }
92            #[cfg(feature = "webp-encode")]
93            EncodedImageFormat::WEBP => {
94                use super::webp_encoder;
95                let mut opts = webp_encoder::Options::default();
96                if quality == 100 {
97                    opts.compression = webp_encoder::Compression::Lossless;
98                    opts.quality = 75.0;
99                } else {
100                    opts.compression = webp_encoder::Compression::Lossy;
101                    opts.quality = quality as _;
102                }
103                webp_encoder::encode(bitmap, &mut data, &opts)
104            }
105            _ => false,
106        }
107        .then_some(data)
108    }
109
110    pub fn bitmap(
111        bitmap: &Bitmap,
112        format: EncodedImageFormat,
113        quality: impl Into<Option<u32>>,
114    ) -> Option<Vec<u8>> {
115        let pixels = bitmap.peek_pixels()?;
116        pixmap(&pixels, format, quality)
117    }
118
119    pub fn image<'a>(
120        context: impl Into<Option<&'a mut crate::gpu::DirectContext>>,
121        image: &crate::Image,
122        image_format: EncodedImageFormat,
123        quality: impl Into<Option<u32>>,
124    ) -> Option<crate::Data> {
125        let quality = quality.into().unwrap_or(100).clamp(0, 100);
126        let _ = quality;
127        match image_format {
128            #[cfg(feature = "jpeg")]
129            EncodedImageFormat::JPEG => {
130                let opts = jpeg_encoder::Options {
131                    quality,
132                    ..jpeg_encoder::Options::default()
133                };
134                jpeg_encoder::encode_image(context, image, &opts)
135            }
136            EncodedImageFormat::PNG => {
137                let opts = png_encoder::Options::default();
138                png_encoder::encode_image(context, image, &opts)
139            }
140            #[cfg(feature = "webp-encode")]
141            EncodedImageFormat::WEBP => {
142                use super::webp_encoder;
143                let mut opts = webp_encoder::Options::default();
144                if quality == 100 {
145                    opts.compression = webp_encoder::Compression::Lossless;
146                    opts.quality = 75.0;
147                } else {
148                    opts.compression = webp_encoder::Compression::Lossy;
149                    opts.quality = quality as _;
150                }
151                webp_encoder::encode_image(context, image, &opts)
152            }
153            _ => None,
154        }
155    }
156
157    /// A keyword / text pair encoded as a comment into the `tEXt` ancillary chunk of a PNG.
158    #[derive(Debug, Clone, PartialEq, Eq)]
159    pub struct Comment {
160        /// The keyword of the comment.
161        pub keyword: String,
162        /// The text of the comment.
163        pub text: String,
164    }
165
166    impl Comment {
167        pub fn new(keyword: impl Into<String>, text: impl Into<String>) -> Self {
168            Self {
169                keyword: keyword.into(),
170                text: text.into(),
171            }
172        }
173    }
174
175    pub(crate) mod comments {
176        use std::ffi::CString;
177
178        use crate::DataTable;
179
180        use super::Comment;
181
182        pub fn to_data_table(comments: &[Comment]) -> Option<DataTable> {
183            let mut comments_c = Vec::with_capacity(comments.len() * 2);
184            for comment in comments {
185                comments_c.push(CString::new(comment.keyword.as_str()).ok()?);
186                comments_c.push(CString::new(comment.text.as_str()).ok()?);
187            }
188            let slices: Vec<&[u8]> = comments_c.iter().map(|c| c.as_bytes_with_nul()).collect();
189            Some(DataTable::from_slices(&slices))
190        }
191    }
192}