From b20bc1f7d83a001054699da0c3f79a3fe97a8c29 Mon Sep 17 00:00:00 2001 From: Jonas Klesen Date: Mon, 17 Apr 2023 00:48:36 +0200 Subject: [PATCH] Rewrite shrink_and_paste_on_blank function --- iz_helpers/image.py | 33 ++++++++++++--------------------- 1 file changed, 12 insertions(+), 21 deletions(-) diff --git a/iz_helpers/image.py b/iz_helpers/image.py index 8ac7b06..d84901a 100644 --- a/iz_helpers/image.py +++ b/iz_helpers/image.py @@ -1,32 +1,23 @@ -import requests from PIL import Image -import numpy as np - def shrink_and_paste_on_blank(current_image, mask_width, mask_height): """ Decreases size of current_image by mask_width pixels from each side, - then adds a mask_width width transparent frame, - so that the image the function returns is the same size as the input. + then adds a mask_width width transparent frame, + so that the image the function returns is the same size as the input. :param current_image: input image to transform :param mask_width: width in pixels to shrink from each side + :param mask_height: height in pixels to shrink from each side """ - height = current_image.height - width = current_image.width + # calculate new dimensions + width, height = current_image.size + new_width = width - 2 * mask_width + new_height = height - 2 * mask_height - # shrink down by mask_width - prev_image = current_image.resize( - (width-2*mask_width, height-2*mask_height)) - prev_image = prev_image.convert("RGBA") - prev_image = np.array(prev_image) + # resize and paste onto blank image + prev_image = current_image.resize((new_width, new_height)) + blank_image = Image.new("RGBA", (width, height), (0, 0, 0, 1)) + blank_image.paste(prev_image, (mask_width, mask_height)) - # create blank non-transparent image - blank_image = np.array(current_image.convert("RGBA"))*0 - blank_image[:, :, 3] = 1 - - # paste shrinked onto blank - blank_image[mask_height:height-mask_height,mask_width:width-mask_width :] = prev_image - prev_image = Image.fromarray(blank_image) - - return prev_image + return blank_image