Skip to content

Commit e279c4b

Browse files
committed
read_region() fixes for zero and negative sizes
1 parent 976c577 commit e279c4b

File tree

2 files changed

+13
-5
lines changed

2 files changed

+13
-5
lines changed

openslide/__init__.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -324,9 +324,8 @@ def read_region(self, location, layer, size):
324324
size: (width, height) tuple giving the region size."""
325325
if layer != 0:
326326
raise OpenSlideError("Invalid layer")
327-
for s in size:
328-
if s <= 0:
329-
raise OpenSlideError("Size must be positive")
327+
if ['fail' for s in size if s < 0]:
328+
raise OpenSlideError("Size %s must be non-negative" % (size,))
330329
# Any corner of the requested region may be outside the bounds of
331330
# the image. Create a transparent tile of the correct size and
332331
# paste the valid part of the region into the correct location.
@@ -335,8 +334,8 @@ def read_region(self, location, layer, size):
335334
image_bottomright = [max(0, min(l + s - 1, limit - 1))
336335
for l, s, limit in zip(location, size, self._image.size)]
337336
tile = Image.new("RGBA", size, (0,) * 4)
338-
if 0 not in [br - tl for tl, br in
339-
zip(image_topleft, image_bottomright)]:
337+
if not ['fail' for tl, br in zip(image_topleft, image_bottomright)
338+
if br - tl < 0]: # "< 0" not a typo
340339
# Crop size is greater than zero in both dimensions.
341340
# PIL thinks the bottom right is the first *excluded* pixel
342341
crop = self._image.crop(image_topleft +

openslide/lowlevel.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,15 @@ def get_layer_dimensions(slide, layer):
122122
[_OpenSlide, POINTER(c_uint32), c_int64, c_int64, c_int32, c_int64,
123123
c_int64])
124124
def read_region(slide, x, y, layer, w, h):
125+
if w < 0 or h < 0:
126+
# OpenSlide would catch this, but not before we tried to allocate
127+
# a negative-size buffer
128+
raise OpenSlideError(
129+
"negative width (%d) or negative height (%d) not allowed" % (
130+
w, h))
131+
if w == 0 or h == 0:
132+
# PIL.Image.frombuffer() would raise an exception
133+
return PIL.Image.new('RGBA', (w, h))
125134
buf = (w * h * c_uint32)()
126135
_read_region(slide, buf, x, y, layer, w, h)
127136
return _load_image(buf, (w, h))

0 commit comments

Comments
 (0)