From 3b34bad92074df9c8cd17ae76b74e54ce4d88ee6 Mon Sep 17 00:00:00 2001 From: kyinhub Date: Sat, 25 Jul 2026 11:08:50 -0700 Subject: [PATCH] fix: validate image reader frame indices Signed-off-by: kyinhub --- src/highdicom/io.py | 13 +++++++++++-- tests/test_io.py | 8 ++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/highdicom/io.py b/src/highdicom/io.py index d7b938cb..95cd1efd 100644 --- a/src/highdicom/io.py +++ b/src/highdicom/io.py @@ -697,12 +697,18 @@ def read_frame_raw(self, index: int) -> bytes: Raises ------ + ValueError + When `index` is less than 0 or greater than or equal to the number + of frames. OSError When frame could not be read """ - if index > self.number_of_frames: - raise ValueError('Frame index exceeds number of frames in image.') + if index < 0 or index >= self.number_of_frames: + raise ValueError( + 'Frame index must be greater than or equal to 0 and less ' + 'than the number of frames in the image.' + ) logger.debug(f'read frame #{index}') frame_offset = self._offset_table[index] @@ -755,6 +761,9 @@ def read_frame(self, index: int, correct_color: bool = True) -> np.ndarray: Raises ------ + ValueError + When `index` is less than 0 or greater than or equal to the number + of frames. OSError When frame could not be read diff --git a/tests/test_io.py b/tests/test_io.py index 4c2e8347..afdae983 100644 --- a/tests/test_io.py +++ b/tests/test_io.py @@ -94,6 +94,14 @@ def test_read_float_pixel_data(self): pixel_array[frame_index], ) + def test_reject_out_of_range_frame_indices(self): + filename = str(self._test_dir.joinpath('ct_image.dcm')) + with ImageFileReader(filename) as reader: + with pytest.raises(ValueError, match="Frame index"): + reader.read_frame_raw(-1) + with pytest.raises(ValueError, match="Frame index"): + reader.read_frame_raw(reader.number_of_frames) + def test_read_multi_frame_ct_image_native(self): filename = str(get_testdata_file('eCT_Supplemental.dcm')) dataset = dcmread(filename)