Resizing an image to smaller size
Resizing images to smaller dimension to satisfy the file size or height/width requirements is something we have faced multiple times. Most of the online tools which I previously used were full of advertisments, and even required to login which is something I hated a lot. Today I learned to do this tedious job with python and it's pretty easy also.
Library used: Pillow
1
import os, sys
2
from PIL import Image
3
4
size = (720, 720)
5
6
for infile in sys.argv[1:]:
7
outfile = os.path.splitext(infile)[0] + f"{size[0]}.jpg"
8
if infile != outfile:
9
try:
10
with Image.open(infile) as im:
11
im.thumbnail(size)
12
im.save(outfile, "JPEG")
13
except OSError:
14
print("cannot create thumbnail for", infile)
Copied!
Save file as resize.py and run the script with:
python3 resize.py image.jpg
Thanks to Jishnu and Rajeesh, I learned there is another tool called ImageMagick. It can also resize images, along with a ton more other cool stuff.
Try image magic, I think it is built into most distros (if not, easy to install via system package manager) and supports more than 200 formats. Easy to use as well.— Jishnu (@jishnu7) July 20, 2021
To Install ImageMagick in your debian based distro:
1
sudo apt install imagemagick
Copied!
To resize images with height, width use the option:
1
convert -resize 300x720 image.jpg resized_image.jpg
Copied!
You can resize also based on the quality as follows:
1
convert -quality 50 image.jpg resized_image.jpg
Copied!
Copy link