1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
use jpeg_decoder::{Decoder, PixelFormat as JpegFormat};

use crate::colorconvert::rgb;
use crate::format::{ImageFormat, PixelFormat};

pub fn convert_to_rgb(
    src: &[u8],
    _src_fmt: &ImageFormat,
    dst: &mut Vec<u8>,
) -> Result<(), &'static str> {
    let mut decoder = Decoder::new(src);
    let data = match decoder.decode() {
        Ok(data) => data,
        Err(_) => return Err("failed to decode JPEG"),
    };

    let info = match decoder.info() {
        Some(info) => info,
        None => return Err("failed to read JPEG metadata"),
    };

    match info.pixel_format {
        JpegFormat::RGB24 => {
            *dst = data;
            Ok(())
        }
        _ => Err("cannot handle JPEG format"),
    }
}

pub fn convert_to_bgr(
    src: &[u8],
    src_fmt: &ImageFormat,
    dst: &mut Vec<u8>,
) -> Result<(), &'static str> {
    let mut rgb = Vec::new();
    convert_to_rgb(src, src_fmt, &mut rgb)?;
    rgb::convert_to_bgr(&rgb, src_fmt, dst)
}

pub fn convert(
    src: &[u8],
    src_fmt: &ImageFormat,
    dst: &mut Vec<u8>,
    dst_fmt: &PixelFormat,
) -> Result<(), &'static str> {
    match dst_fmt {
        PixelFormat::Bgr(24) => convert_to_bgr(src, src_fmt, dst),
        PixelFormat::Rgb(24) => convert_to_rgb(src, src_fmt, dst),
        _ => Err("cannot handle target format"),
    }
}