2
votes

I want to work with a bunch of images (100+) and I need to keep their aspect ratios (which varies between each other), but resize them to be a maximum of 1000x1000 and have a maximum file size of 100kb.

I have tried the "optimize-images" package but I couldn't get the results I wanted because I couldn't be specific enough. I also tried resizing with imageio, but the size issue remains. I have read different sources and replies to similar issues, but have found no way of doing this.

import imageio
import os

os.chdir("C:\\Users\\abc123\\Pictures\\Resize")

im = imageio.imread("a.jpg")

small = transform.resize(im, (1000,1000), mode="symmetric", preserve_range=True)

Ideally, I will use the walk() method to find all the images in the folder, resize them to 1000x1000, maintain the aspect ratio by filling with blank the differential between the final size and the resized image, and finally apply a 0.8 or 0.75 quality reduction until the file size is =< 100 kb. I realize my code is very basic, but I'm mostly looking for directions/inspiration for how I could tackle this problem. Thanks in advance!

1
You can find half your answer at stackoverflow.com/q/13407717/5987 - Mark Ransom
And maybe this will help too: stackoverflow.com/a/3008966/5987 if you combine it with resize(). - Mark Ransom
You can do it without writing any code, just in Terminal with ImageMagick. Make a copy of a few images in a separate directory and try it magick -resize 1000x1000 -define jpeg:extent=100KB *.jpg - Mark Setchell

1 Answers

1
votes

You could use skimage library.

import numpy as np
from skimage import data, color
from skimage.transform import rescale, resize

grayimage = color.rgb2gray(data.astronaut())
image_rescaled = rescale(grayimage, 1.0 / 4.0, anti_aliasing=False, multichannel = False)
image_resized = resize(grayimage, (grayimage.shape[0] / 4, grayimage.shape[1] / 4),
                       anti_aliasing=True)
plt.imshow(np.hstack([image_rescaled, image_resized]))
plt.title('Rescaled'+ ''.join([" "]*30) +'Resized')
plt.show()

Output:
enter image description here

Saving Image with Reduced File Size

For controlling the file size while saving the image to your file system, you could use PIL library with optimize=True and quality=some_number. See this thread: How to reduce the image file size using PIL.

References

HowTo: Rescale and Resize using skimage Library