How to reduce the image file size using PIL

后端 未结 4 1373
抹茶落季
抹茶落季 2020-11-28 03:11

I am using PIL to resize the images there by converting larger images to smaller ones. Are there any standard ways to reduce the file size of the image without losing the qu

4条回答
  •  醉酒成梦
    2020-11-28 04:11

    The main image manager in PIL is PIL's Image module.

    from PIL import Image
    import math
    
    foo = Image.open("path\\to\\image.jpg")
    x, y = foo.size
    x2, y2 = math.floor(x-50), math.floor(y-20)
    foo = foo.resize((x2,y2),Image.ANTIALIAS)
    foo.save("path\\to\\save\\image_scaled.jpg",quality=95)
    

    You can add optimize=True to the arguments of you want to decrease the size even more, but optimize only works for JPEG's and PNG's. For other image extensions, you could decrease the quality of the new saved image. You could change the size of the new image by just deleting a bit of code and defining the image size and you can only figure out how to do this if you look at the code carefully. I defined this size:

    x, y = foo.size
    x2, y2 = math.floor(x-50), math.floor(y-20)
    

    just to show you what is (almost) normally done with horizontal images. For vertical images you might do:

    x, y = foo.size
    x2, y2 = math.floor(x-20), math.floor(y-50)
    

    . Remember, you can still delete that bit of code and define a new size.

提交回复
热议问题