Skip to content

Commit 19c8123

Browse files
committed
Add GenericImageView::try_view
1 parent 80b2124 commit 19c8123

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

src/images/generic_image.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,10 @@ pub trait GenericImageView {
7676
/// Returns a subimage that is an immutable view into this image.
7777
/// You can use [`GenericImage::sub_image`] if you need a mutable view instead.
7878
/// The coordinates set the position of the top left corner of the view.
79+
///
80+
/// # Panics
81+
///
82+
/// Panics if the dimensions provided fall out of bounds.
7983
fn view(&self, x: u32, y: u32, width: u32, height: u32) -> SubImage<&Self>
8084
where
8185
Self: Sized,
@@ -84,6 +88,29 @@ pub trait GenericImageView {
8488
assert!(u64::from(y) + u64::from(height) <= u64::from(self.height()));
8589
SubImage::new(self, x, y, width, height)
8690
}
91+
92+
/// Returns a subimage that is an immutable view into this image so long as
93+
/// the provided coordinates and dimensions are within the bounds of this Image.
94+
fn try_view(
95+
&self,
96+
x: u32,
97+
y: u32,
98+
width: u32,
99+
height: u32,
100+
) -> Result<SubImage<&Self>, ImageError>
101+
where
102+
Self: Sized,
103+
{
104+
if u64::from(x) + u64::from(width) > u64::from(self.width())
105+
|| u64::from(y) + u64::from(height) > u64::from(self.height())
106+
{
107+
Err(ImageError::Parameter(ParameterError::from_kind(
108+
ParameterErrorKind::DimensionMismatch,
109+
)))
110+
} else {
111+
Ok(SubImage::new(self, x, y, width, height))
112+
}
113+
}
87114
}
88115

89116
/// Immutable pixel iterator

0 commit comments

Comments
 (0)