Skip to content

Commit

Permalink
feat: Resize image (#354)
Browse files Browse the repository at this point in the history
Closes #283

### Summary of Changes

* Added a new method `resize` to `Image` that takes parameters
`new_width` and `new_height` and returns a new, resized `Image`. The
original image is not changed.

---------

Co-authored-by: jxnior01 <[email protected]>
Co-authored-by: megalinter-bot <[email protected]>
Co-authored-by: Severin Paul Höfer <[email protected]>
  • Loading branch information
4 people authored Jun 16, 2023
1 parent d75ae96 commit 3a971ca
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/safeds/data/image/containers/_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,3 +151,28 @@ def _repr_png_(self) -> bytes | None:
self._image.save(buffer, format="png")
buffer.seek(0)
return buffer.read()

# ------------------------------------------------------------------------------------------------------------------
# Transformations
# ------------------------------------------------------------------------------------------------------------------

def resize(self, new_width: int, new_height: int) -> Image:
"""
Return the resized image.
Returns
-------
result : Image
The image with the given width and height
"""
data = io.BytesIO()
repr_png = self._repr_png_()
repr_jpeg = self._repr_jpeg_()
if repr_png is not None:
data = io.BytesIO(repr_png)
elif repr_jpeg is not None:
data = io.BytesIO(repr_jpeg)

new_image = Image(data, self._format)
new_image._image = new_image._image.resize((new_width, new_height))
return new_image
29 changes: 29 additions & 0 deletions tests/safeds/data/image/containers/test_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,3 +152,32 @@ def test_should_return_bytes_if_image_is_png(self, image: Image) -> None:
)
def test_should_return_none_if_image_is_not_png(self, image: Image) -> None:
assert image._repr_png_() is None


class TestResize:
@pytest.mark.parametrize(
("image", "new_width", "new_height", "new_size"),
[
(
Image.from_jpeg_file(resolve_resource_path("image/white_square.jpg")),
2,
3,
(2, 3),
),
(
Image.from_png_file(resolve_resource_path("image/white_square.png")),
2,
3,
(2, 3),
),
],
ids=[".jpg", ".png"],
)
def test_should_return_resized_image(
self,
image: Image,
new_width: int,
new_height: int,
new_size: tuple[int, int],
) -> None:
assert image.resize(new_width, new_height)._image.size == new_size

0 comments on commit 3a971ca

Please sign in to comment.