Skip to main content

caesium/
lib.rs

1extern crate alloc;
2
3use std::fs;
4use std::fs::File;
5use std::io::Write;
6
7#[cfg(feature = "tiff")]
8use crate::parameters::TiffCompression::{Deflate, Lzw, Packbits};
9use crate::parameters::{CSParameters, TiffDeflateLevel};
10use crate::utils::{get_filetype_from_memory, get_filetype_from_path};
11use error::CaesiumError;
12
13mod convert;
14pub mod error;
15#[cfg(feature = "gif")]
16mod gif;
17mod interface;
18#[cfg(feature = "jpg")]
19mod jpeg;
20pub mod parameters;
21#[cfg(feature = "png")]
22mod png;
23mod resize;
24#[cfg(feature = "tiff")]
25mod tiff;
26mod utils;
27#[cfg(feature = "webp")]
28mod webp;
29
30/// Compresses an image file from the input path and writes the compressed image to the output path.
31///
32/// # Arguments
33///
34/// * `input_path` - A string representing the path to the input image file.
35/// * `output_path` - A string representing the path to the output compressed image file.
36/// * `parameters` - A reference to `CSParameters` containing compression settings.
37///
38/// # Returns
39///
40/// * `Result<(), CaesiumError>` - Returns `Ok(())` if compression is successful, otherwise returns a `CaesiumError`.
41pub fn compress(input_path: String, output_path: String, parameters: &CSParameters) -> error::Result<()> {
42    validate_parameters(parameters)?;
43    let file_type = get_filetype_from_path(&input_path);
44
45    match file_type {
46        #[cfg(feature = "jpg")]
47        SupportedFileTypes::Jpeg => {
48            jpeg::compress(input_path, output_path, parameters)?;
49        }
50        #[cfg(feature = "png")]
51        SupportedFileTypes::Png => {
52            png::compress(input_path, output_path, parameters)?;
53        }
54        #[cfg(feature = "webp")]
55        SupportedFileTypes::WebP => {
56            webp::compress(input_path, output_path, parameters)?;
57        }
58        #[cfg(feature = "gif")]
59        SupportedFileTypes::Gif => {
60            gif::compress(input_path, output_path, parameters)?;
61        }
62        #[cfg(feature = "tiff")]
63        SupportedFileTypes::Tiff => {
64            tiff::compress(input_path, output_path, parameters)?;
65        }
66        _ => {
67            return Err(CaesiumError {
68                message: "Unknown file type or file not found".into(),
69                code: 10000,
70            });
71        }
72    }
73
74    Ok(())
75}
76
77/// Compresses an image file in memory and returns the compressed image as a byte vector.
78///
79/// # Arguments
80///
81/// * `in_file` - A vector of bytes representing the input image file.
82/// * `parameters` - A reference to `CSParameters` containing compression settings.
83///
84/// # Returns
85///
86/// * `Result<Vec<u8>, CaesiumError>` - Returns a vector of bytes representing the compressed image if successful, otherwise returns a `CaesiumError`.
87pub fn compress_in_memory(in_file: Vec<u8>, parameters: &CSParameters) -> error::Result<Vec<u8>> {
88    compress_in_memory_with_rotation(in_file, parameters, None)
89}
90
91pub(crate) fn compress_in_memory_with_rotation(
92    in_file: Vec<u8>,
93    parameters: &CSParameters,
94    source_orientation: Option<u16>,
95) -> error::Result<Vec<u8>> {
96    let file_type = get_filetype_from_memory(in_file.as_slice());
97    let compressed_file = match file_type {
98        #[cfg(feature = "jpg")]
99        SupportedFileTypes::Jpeg => jpeg::compress_in_memory(&in_file, parameters, source_orientation)?,
100        #[cfg(feature = "png")]
101        SupportedFileTypes::Png => png::compress_in_memory(&in_file, parameters, source_orientation)?,
102        #[cfg(feature = "gif")]
103        SupportedFileTypes::Gif => gif::compress_in_memory(&in_file, parameters)?,
104        #[cfg(feature = "webp")]
105        SupportedFileTypes::WebP => webp::compress_in_memory(&in_file, parameters, source_orientation)?,
106        #[cfg(feature = "tiff")]
107        SupportedFileTypes::Tiff => tiff::compress_in_memory(&in_file, parameters, source_orientation)?,
108        _ => {
109            return Err(CaesiumError {
110                message: "Format not supported for compression in memory".into(),
111                code: 10200,
112            });
113        }
114    };
115
116    Ok(compressed_file)
117}
118
119/// Compresses an image file in memory up to a specified size and returns the compressed image as a byte vector.
120///
121/// # Arguments
122///
123/// * `in_file` - A vector of bytes representing the input image file.
124/// * `parameters` - A mutable reference to `CSParameters` containing compression settings.
125/// * `max_output_size` - The maximum size of the output compressed image in bytes.
126/// * `return_smallest` - A boolean indicating whether to return the smallest compressed image if the desired size is not achieved.
127///
128/// # Returns
129///
130/// * `Result<Vec<u8>, CaesiumError>` - Returns a vector of bytes representing the compressed image if successful, otherwise returns a `CaesiumError`.
131pub fn compress_to_size_in_memory(
132    in_file: Vec<u8>,
133    parameters: &mut CSParameters,
134    max_output_size: usize,
135    return_smallest: bool,
136) -> error::Result<Vec<u8>> {
137    let file_type = get_filetype_from_memory(&in_file);
138
139    let tolerance_percentage = 2;
140    let tolerance = max_output_size * tolerance_percentage / 100;
141    let mut quality = 80;
142    let mut last_less = 0;
143    let mut last_high = 101;
144    let max_tries: u32 = 10;
145    let mut tries: u32 = 0;
146
147    let compressed_file = match file_type {
148        #[cfg(feature = "tiff")]
149        SupportedFileTypes::Tiff => {
150            let algorithms = [Lzw, Packbits];
151            parameters.tiff.deflate_level = TiffDeflateLevel::Best;
152            parameters.tiff.algorithm = Deflate;
153            let mut smallest_result = tiff::compress_in_memory(&in_file, parameters, None)?;
154            for tc in algorithms {
155                parameters.tiff.algorithm = tc;
156                let result = tiff::compress_in_memory(&in_file, parameters, None)?;
157                if result.len() < smallest_result.len() {
158                    smallest_result = result;
159                }
160            }
161            return if return_smallest || smallest_result.len() <= max_output_size {
162                Ok(smallest_result)
163            } else {
164                Err(CaesiumError {
165                    message: "Cannot compress to desired quality".into(),
166                    code: 10202,
167                })
168            };
169        }
170        _ => loop {
171            if tries >= max_tries {
172                return Err(CaesiumError {
173                    message: "Max tries reached".into(),
174                    code: 10201,
175                });
176            }
177
178            let compressed_file: Vec<u8> = match file_type {
179                #[cfg(feature = "jpg")]
180                SupportedFileTypes::Jpeg => {
181                    parameters.jpeg.quality = quality;
182                    jpeg::compress_in_memory(&in_file, parameters, None)?
183                }
184                #[cfg(feature = "png")]
185                SupportedFileTypes::Png => {
186                    parameters.png.quality = quality;
187                    png::compress_in_memory(&in_file, parameters, None)?
188                }
189                #[cfg(feature = "gif")]
190                SupportedFileTypes::Gif => {
191                    parameters.gif.quality = quality;
192                    gif::compress_in_memory(&in_file, parameters)?
193                }
194                #[cfg(feature = "webp")]
195                SupportedFileTypes::WebP => {
196                    parameters.webp.quality = quality;
197                    webp::compress_in_memory(&in_file, parameters, None)?
198                }
199                _ => {
200                    return Err(CaesiumError {
201                        message: "Format not supported for compression to size".into(),
202                        code: 10200,
203                    });
204                }
205            };
206
207            let compressed_file_size = compressed_file.len();
208
209            if compressed_file_size <= max_output_size && max_output_size - compressed_file_size < tolerance {
210                break compressed_file;
211            }
212
213            if compressed_file_size <= max_output_size {
214                last_less = quality;
215            } else {
216                last_high = quality;
217            }
218            let last_quality = quality;
219            quality = ((last_high + last_less) / 2).clamp(1, 100);
220            if last_quality == quality {
221                if quality == 1 && last_high == 1 {
222                    return if return_smallest {
223                        Ok(compressed_file)
224                    } else {
225                        Err(CaesiumError {
226                            message: "Cannot compress to desired quality".into(),
227                            code: 10202,
228                        })
229                    };
230                }
231
232                break compressed_file;
233            }
234
235            tries += 1;
236        },
237    };
238
239    Ok(compressed_file)
240}
241
242/// Compresses an image file from the input path up to a specified size and writes the compressed image to the output path.
243///
244/// # Arguments
245///
246/// * `input_path` - A string representing the path to the input image file.
247/// * `output_path` - A string representing the path to the output compressed image file.
248/// * `parameters` - A mutable reference to `CSParameters` containing compression settings.
249/// * `max_output_size` - The maximum size of the output compressed image in bytes.
250/// * `return_smallest` - A boolean indicating whether to return the smallest compressed image if the desired size is not achieved.
251///
252/// # Returns
253///
254/// * `Result<(), CaesiumError>` - Returns `Ok(())` if compression is successful, otherwise returns a `CaesiumError`.
255pub fn compress_to_size(
256    input_path: String,
257    output_path: String,
258    parameters: &mut CSParameters,
259    max_output_size: usize,
260    return_smallest: bool,
261) -> error::Result<()> {
262    let in_file = fs::read(input_path.clone()).map_err(|e| CaesiumError {
263        message: e.to_string(),
264        code: 10201,
265    })?;
266    let original_size = in_file.len();
267
268    // If we resize, we should always go for at least a round of compression
269    if !(parameters.width > 0 || parameters.height > 0) && original_size <= max_output_size {
270        if input_path == output_path {
271            return Ok(());
272        }
273        fs::copy(input_path, output_path).map_err(|e| CaesiumError {
274            message: e.to_string(),
275            code: 10202,
276        })?;
277        return Ok(());
278    }
279
280    let compressed_file = compress_to_size_in_memory(in_file, parameters, max_output_size, return_smallest)?;
281    let mut out_file = File::create(output_path).map_err(|e| CaesiumError {
282        message: e.to_string(),
283        code: 10203,
284    })?;
285    out_file.write_all(&compressed_file).map_err(|e| CaesiumError {
286        message: e.to_string(),
287        code: 10204,
288    })?;
289
290    Ok(())
291}
292
293/// Converts an image file from the input path to a specified format and writes the converted image to the output path.
294///
295/// # Arguments
296///
297/// * `input_path` - A string representing the path to the input image file.
298/// * `output_path` - A string representing the path to the output converted image file.
299/// * `parameters` - A reference to `CSParameters` containing conversion settings.
300/// * `format` - The target format to convert the image to.
301///
302/// # Returns
303///
304/// * `Result<(), CaesiumError>` - Returns `Ok(())` if conversion is successful, otherwise returns a `CaesiumError`.
305pub fn convert(
306    input_path: String,
307    output_path: String,
308    parameters: &CSParameters,
309    format: SupportedFileTypes,
310) -> error::Result<()> {
311    let file_type = get_filetype_from_path(&input_path);
312
313    if file_type == format {
314        return Err(CaesiumError {
315            message: "Cannot convert to the same format".into(),
316            code: 10406,
317        });
318    }
319
320    let in_file = fs::read(input_path).map_err(|e| CaesiumError {
321        message: e.to_string(),
322        code: 10410,
323    })?;
324    let output_buffer = convert_in_memory(in_file, parameters, format).map_err(|e| CaesiumError {
325        message: e.to_string(),
326        code: 10411,
327    })?;
328
329    let mut out_file = File::create(output_path).map_err(|e| CaesiumError {
330        message: e.to_string(),
331        code: 10412,
332    })?;
333
334    out_file.write_all(&output_buffer).map_err(|e| CaesiumError {
335        message: e.to_string(),
336        code: 10413,
337    })?;
338
339    Ok(())
340}
341
342/// Converts an image file in memory to a specified format and returns the converted image as a byte vector.
343///
344/// # Arguments
345///
346/// * `in_file` - A vector of bytes representing the input image file.
347/// * `parameters` - A reference to `CSParameters` containing conversion settings.
348/// * `format` - The target format to convert the image to.
349///
350/// # Returns
351///
352/// * `Result<Vec<u8>, CaesiumError>` - Returns a vector of bytes representing the converted image if successful, otherwise returns a `CaesiumError`.
353pub fn convert_in_memory(
354    in_file: Vec<u8>,
355    parameters: &CSParameters,
356    format: SupportedFileTypes,
357) -> Result<Vec<u8>, CaesiumError> {
358    convert::convert_in_memory(in_file, format, parameters)
359}
360
361fn validate_parameters(parameters: &CSParameters) -> error::Result<()> {
362    if parameters.jpeg.quality > 100 {
363        return Err(CaesiumError {
364            message: "Invalid JPEG quality value".into(),
365            code: 10001,
366        });
367    }
368
369    if parameters.png.quality > 100 {
370        return Err(CaesiumError {
371            message: "Invalid PNG quality value".into(),
372            code: 10002,
373        });
374    }
375
376    if parameters.png.optimization_level > 6 {
377        return Err(CaesiumError {
378            message: "Invalid PNG optimization level".into(),
379            code: 10006,
380        });
381    }
382
383    if parameters.gif.quality > 100 || parameters.gif.quality < 1 {
384        return Err(CaesiumError {
385            message: "Invalid GIF quality value".into(),
386            code: 10003,
387        });
388    }
389
390    if parameters.webp.quality > 100 {
391        return Err(CaesiumError {
392            message: "Invalid WebP quality value".into(),
393            code: 10004,
394        });
395    }
396
397    Ok(())
398}
399
400#[repr(C)]
401#[derive(PartialEq, Eq, Clone, Copy)]
402pub enum SupportedFileTypes {
403    Jpeg,
404    Png,
405    Gif,
406    WebP,
407    Tiff,
408    Unkn,
409}