Resize the image to the specified size and blacken the margins

I wanted to match all the sizes of the images I had.

First, transform the image at hand so that it is smaller than the specified size without changing the aspect ratio. Since it deforms while maintaining the aspect ratio, there will be a deviation from the specified size vertically or horizontally. I decided to paint the gap black.

It was done using Python and PIL.

code

(Addition) In the comments, @shiracamus added. Please also check!

image.py


from PIL import Image

#Specify vertical and horizontal sizes
width =360
height = 240

#Transform the height and width of the image so that it is smaller than the specified size
img = Image.open("hoge.jpg ")
img.thumbnail((width,height),Image.ANTIALIAS)

#Create a background image to fill in black
bg = Image.new("RGBA",[width,height],(0,0,0,255))

#Place the original image in the center of the background image
bg.paste(img,(int((width-img.size[0])/2),int((height-img.size[1])/2)))

reference

I referred to the following site. Prevent plagiarism! Watermark images using Python Paste image in Python

Finally

Thank you very much.

Recommended Posts

Resize the image to the specified size and blacken the margins
[linux] Split files to the specified size
I tried moving the image to the specified folder by right-clicking and left-clicking
Dot according to the image
Judge the extension and download the image
[Python] How to specify the window display position and size of matplotlib
Start the webcam to take a still image and save it locally
[python] Send the image captured from the webcam to the server and save it
Add lines and text on the image
Use Pillow to make the image transparent and overlay only part of it
I tried to process and transform the image and expand the data for machine learning
Mouse over Matplotlib to display the corresponding image
Try adding fisheye lens distortion to the image
Crop the image to rounded corners with pythonista
Converting the coordinate system to ECEF and geodesy
Image characters and post to slack (python slackbot)
8-bit grayscale Downscaling to images and image contrast
I tried to correct the keystone of the image
Response the resized image using Flask and PILImage
Experiment and leave evidence to determine the specifications.
Recursively search the specified directory to see the file
How to use the grep command to recursively search directories and files to a specified depth