Python: Programmatically resize .jpgs [closed]
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this questionI have a folder of .jpgs files that are all over 2MB in size. I need to upload them to a website but they are WAY too large to show on a website.
Is there a way to resize the actual images in Python &/or to reduce the file size of the jpg开发者_如何学Pythons in python.
Maybe there is a native python library to work with bitmaps &/or jpegs or maybe there is a third party library to do this?
PS: I also know Java & C++, are there any functions(or 3rd party libraries) in those languages that could do this?
Can't get much easier than with PIL:
from PIL import Image
size = 300, 300
im = Image.open('image.jpg')
im.thumbnail(size, Image.ANTIALIAS) # thumbnail maintains aspect ratio
im.save('image_resized.jpg')
This will solve the problem, overwriting all files with the new size:
import cv2
import os
size=50
folder='/home/user/anaconda3/images'
for filename in os.listdir(folder):
img = cv2.imread(os.path.join(folder,filename), cv2.IMREAD_GRAYSCALE)
img2=cv2.resize(img,(size,size))
cv2.imwrite('/home/user/anaconda3/images/'+filename,img2)
精彩评论