programing

PIL을 사용하여 이미지 파일 크기를 줄이는 방법

muds 2023. 8. 24. 22:30
반응형

PIL을 사용하여 이미지 파일 크기를 줄이는 방법

저는 PIL을 사용하여 큰 이미지를 작은 이미지로 변환하여 이미지 크기를 조정하고 있습니다.화질을 크게 떨어뜨리지 않고 이미지의 파일 크기를 줄이는 표준 방법이 있습니까?이미지의 원래 크기가 100KB라고 가정합니다.특히 PNG 및 JPEG 형식의 경우 5 또는 10kB 정도로 줄이고 싶습니다.

JPEG와 PNG를 저장하기 위한 내장 매개변수는 다음과 같습니다.optimize.

 from PIL import Image

 foo = Image.open('path/to/image.jpg')  # My image is a 200x374 jpeg that is 102kb large
 foo.size  # (200, 374)
 
 # downsize the image with an ANTIALIAS filter (gives the highest quality)
 foo = foo.resize((160,300),Image.ANTIALIAS)
 
 foo.save('path/to/save/image_scaled.jpg', quality=95)  # The saved downsized image size is 24.8kb
 
 foo.save('path/to/save/image_scaled_opt.jpg', optimize=True, quality=95)  # The saved downsized image size is 22.9kb

optimizeflag는 가능한 한 크기를 줄일 수 있는 방법을 찾기 위해 이미지에 추가적인 패스를 할 것입니다. 1.9kb는 많지 않아 보일 수 있지만 수백/수십 개 이상의 사진이 추가될 수 있습니다.

이제 5kb에서 10kb로 낮추려면 저장 옵션에서 품질 값을 변경할 수 있습니다.이 경우 95가 아닌 85를 사용하면 다음과 같은 결과를 얻을 수 있습니다.최적화되지 않음: 15.1kb 최적화됨: 14.3kb 품질 75(인수를 제외한 경우 기본값)를 사용하면 다음을 얻을 수 있습니다.최적화되지 않음: 11.8kb 최적화됨: 11.2kb

품질에 큰 영향을 받지 않고 파일 크기도 훨씬 작기 때문에 최적화된 품질 85를 선호합니다.

예를 들어 Book이라는 모델과 'cover_pic'이라는 필드가 있다고 가정해 보겠습니다. 이 경우 다음을 수행하여 이미지를 압축할 수 있습니다.

from PIL import Image
b = Book.objects.get(title='Into the wild')
image = Image.open(b.cover_pic.path)
image.save(b.image.path,quality=20,optimize=True)

그것이 누구든 그것에 걸려 넘어지는 것을 돕기를 바랍니다.

PIL의 이미지 모듈의 축소 이미지 기능을 참조하십시오.이 도구를 사용하여 파일의 작은 버전을 다양한 파일 형식으로 저장할 수 있으며 가능한 한 많은 품질을 유지하려면ANTIALIAS필터를 사용합니다.

그 외에 원하는 최대 사이즈를 지정할 수 있는 방법이 있는지 잘 모르겠습니다.물론 특정 크기가 충족될 때까지 여러 버전의 파일을 다양한 품질로 저장하고 나머지는 삭제하고 원하는 이미지를 제공하는 기능을 작성할 수 있습니다.

의 기본 이미지 관리자PIL이라PILImage모듈.

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)

추가할 수 있습니다.optimize=TrueJPEG 및 PNG에 대해서만 작업을 최적화할 수 있습니다.다른 이미지 확장의 경우 새 저장된 이미지의 품질을 낮출 수 있습니다.코드를 조금 삭제하고 이미지 크기를 정의하기만 하면 새 이미지의 크기를 변경할 수 있으며 코드를 주의 깊게 살펴봐야만 이 방법을 알 수 있습니다.이 크기를 정의했습니다.

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

일반적으로 수평 이미지로 수행되는 작업을 보여줍니다.수직 이미지의 경우 다음 작업을 수행할 수 있습니다.

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

해당 코드 비트를 삭제하고 새 크기를 정의할 수 있습니다.

높이를 입니다.with saving it's proportion 크기를 것 또한 다있니습일.

있습니다.two options논리를 요, 은같논하있고습다니를리.first one is how i did in django project,second is on pure python

을 변경할 수 .TARGET_WIDTH한 너비에

django models.py저장 후 됩니다.

from PIL import Image

class Theme(models.Model):
    image = models.ImageField(upload_to='theme_image/')
    
    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        this_image = Image.open(self.image.path)
        width, height = this_image.size
        TARGET_WIDTH = 500
        coefficient = width / 500
        new_height = height / coefficient
        this_image = this_image.resize((int(TARGET_WIDTH),int(new_height)),Image.ANTIALIAS)
        this_image.save(self.image.path,quality=50)

없이foo.py:

from PIL import Image

this_image = Image.open("path\to\your_image.jpg")
width, height = this_image.size
TARGET_WIDTH = 500
coefficient = width / 500
new_height = height / coefficient
this_image = this_image.resize((int(TARGET_WIDTH),int(new_height)),Image.ANTIALIAS)
this_image.save("path\where\to_save\your_image.jpg",quality=50)

이미지 크기를 조정하거나 이미지 품질을 낮출 수 있습니다.여기에 첨부된 몇 가지 예:

Python PIL 이미지 크기 조정

from PIL import Image
WIDTH = 1020
HEIGHT = 720
img = Image.open("my_image.jpg")
resized_img = img.resize((WIDTH, HEIGHT))
resized_img.save("resized_image.jpg")

이미지 해상도 베개 변경

from PIL import Image
size = 7016, 4961
im = Image.open("my_image.png")
im_resized = im.resize(size, Image.ANTIALIAS)
im_resized.save("image_resized.png", "PNG")

또는 사용할 수 있습니다.

im_resized.save("image_resized.png", quality=95, optimize=True)

이미지 크기를 조정하고 JPEG로 저장한 후 품질을 95로 낮추면 최종 출력에서 많은 바이트가 절약됩니다.

image = Image.open("input_file.png")
image = image.resize((WIDTH, HEIGHT))  #smaller width and height than the original

image.save("output_file.jpg", "JPEG", quality=95)

그러나 이미지 크기 <= 100kb는 무조건 가져와야 한다고 가정해 보겠습니다.이 경우 올바른 파일 크기에 도달할 때까지 이미지 품질을 계속 줄여야 합니다.

minimum_quality = 50      # recommended, but optional (set to 0 if you don't want it)

quality = 95      # initial quality
target = 100000   # 100 kb

while True:
    output_buffer = io.BytesIO()    # import io
    image.save(output_buffer, "JPEG", quality=quality)

    file_size = output_buffer.tell()

    if file_size <= target or quality <= minimum_quality:
        output_buffer.close()
        break
    else:
        quality -= 5

image.save(output_image, "JPEG", quality=quality)

보시는 것처럼 임시 버퍼에 이미지를 계속 저장하고 버퍼 크기를 읽어 파일 크기를 알 수 있습니다.

지방이 많은 png(400x400의 경우 1MB 등)이 있는 경우:

__import__("importlib").import_module("PIL.Image").open("out.png").save("out.png")

언급URL : https://stackoverflow.com/questions/10607468/how-to-reduce-the-image-file-size-using-pil

반응형