@@ -24,20 +24,41 @@ impl DecodedSamples {
2424 objects : & dyn ObjectResolver ,
2525 metadata : & ImageMetadata ,
2626 ) -> Result < Self , PdfImageError > {
27- if let Some ( decoded_samples) = Self :: decode_preconverted_jpx ( raw_data, metadata) {
28- return Ok ( decoded_samples) ;
29- }
27+ let decoded_samples = if let Some ( decoded_samples) =
28+ Self :: decode_preconverted_jpx ( raw_data, metadata)
29+ {
30+ decoded_samples
31+ } else if let Some ( decoded_samples) = Self :: decode_preconverted_dct ( raw_data, metadata) {
32+ decoded_samples
33+ } else {
34+ match metadata. color_space . as_ref ( ) {
35+ Some ( ColorSpace :: Indexed ( indexed) ) => {
36+ Self :: decode_indexed ( dictionary, raw_data, objects, metadata, indexed)
37+ }
38+ _ => Self :: decode_direct ( dictionary, raw_data, objects, metadata) ,
39+ } ?
40+ } ;
3041
31- if let Some ( decoded_samples) = Self :: decode_preconverted_dct ( raw_data, metadata) {
32- return Ok ( decoded_samples) ;
42+ decoded_samples. validate ( metadata) ?;
43+ Ok ( decoded_samples)
44+ }
45+
46+ /// Ensures the decoded component stream is large enough for the declared dimensions.
47+ fn validate ( & self , metadata : & ImageMetadata ) -> Result < ( ) , PdfImageError > {
48+ if self . num_color_components == 0 {
49+ return Err ( PdfImageError :: InvalidColorComponentCount ) ;
3350 }
3451
35- match metadata. color_space . as_ref ( ) {
36- Some ( ColorSpace :: Indexed ( indexed) ) => {
37- Self :: decode_indexed ( dictionary, raw_data, objects, metadata, indexed)
38- }
39- _ => Self :: decode_direct ( dictionary, raw_data, objects, metadata) ,
52+ let num_pixels = metadata. width . saturating_mul ( metadata. height ) ;
53+ let expected_bytes = num_pixels. saturating_mul ( self . num_color_components ) ;
54+ if self . image_data . len ( ) < expected_bytes {
55+ return Err ( PdfImageError :: TruncatedImageData {
56+ expected_bytes,
57+ actual_bytes : self . image_data . len ( ) ,
58+ } ) ;
4059 }
60+
61+ Ok ( ( ) )
4162 }
4263
4364 /// Uses DCT decoder output as display samples when the JPEG decoder already converted color.
0 commit comments