Skip to main content

rpdfium_render/
image.rs

1// Derived from PDFium's core/fpdfapi/render/cpdf_imagerenderer.cpp
2// Original: Copyright 2014 The PDFium Authors
3// Licensed under BSD-3-Clause / Apache-2.0
4// See pdfium-upstream/LICENSE for the original license.
5
6//! Decoded image types and the image decoder trait.
7
8use std::collections::HashMap;
9
10use rpdfium_core::{Matrix, Name};
11use rpdfium_graphics::ImageRef;
12use rpdfium_parser::Operand;
13
14use crate::error::RenderError;
15
16/// Format of decoded image pixel data.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum DecodedImageFormat {
19    /// 8-bit grayscale (1 byte per pixel).
20    Gray8,
21    /// 24-bit RGB (3 bytes per pixel).
22    Rgb24,
23    /// 32-bit RGBA (4 bytes per pixel).
24    Rgba32,
25}
26
27/// A decoded image ready for rendering.
28#[derive(Debug, Clone)]
29pub struct DecodedImage {
30    /// Width in pixels.
31    pub width: u32,
32    /// Height in pixels.
33    pub height: u32,
34    /// Raw pixel data in the specified format.
35    pub data: Vec<u8>,
36    /// Pixel format.
37    pub format: DecodedImageFormat,
38}
39
40/// Trait for decoding PDF images at render time.
41///
42/// Implementations resolve image XObject references and inline image data
43/// into decoded pixel buffers.
44pub trait ImageDecoder: Send + Sync {
45    /// Decode an image XObject.
46    fn decode_image(
47        &self,
48        image_ref: &ImageRef,
49        matrix: &Matrix,
50    ) -> Result<DecodedImage, RenderError>;
51
52    /// Decode an inline image.
53    fn decode_inline_image(
54        &self,
55        properties: &HashMap<Name, Operand>,
56        data: &[u8],
57        matrix: &Matrix,
58    ) -> Result<DecodedImage, RenderError>;
59}
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64
65    #[test]
66    fn test_decoded_image_format_eq() {
67        assert_eq!(DecodedImageFormat::Gray8, DecodedImageFormat::Gray8);
68        assert_ne!(DecodedImageFormat::Gray8, DecodedImageFormat::Rgb24);
69    }
70
71    #[test]
72    fn test_decoded_image_clone() {
73        let img = DecodedImage {
74            width: 10,
75            height: 10,
76            data: vec![0; 100],
77            format: DecodedImageFormat::Gray8,
78        };
79        let cloned = img.clone();
80        assert_eq!(cloned.width, 10);
81        assert_eq!(cloned.data.len(), 100);
82    }
83}