PIL을 사용하여 이미지를 조정하고 종횡비를 유지하려면 어떻게해야합니까?

StackOverflow https://stackoverflow.com/questions/273946

문제

내가 놓친 분명한 방법이 있습니까? 나는 단지 축소판을 만들려고 노력하고 있습니다.

도움이 되었습니까?

해결책

최대 크기를 정의합니다. 그런 다음 복용하여 크기 조정 비율을 계산하십시오 min(maxwidth/width, maxheight/height).

적절한 크기는입니다 oldsize*ratio.

물론이를 수행하는 라이브러리 방법도 있습니다. Image.thumbnail.
아래는 (편집 된) 예입니다 PIL 문서.

import os, sys
import Image

size = 128, 128

for infile in sys.argv[1:]:
    outfile = os.path.splitext(infile)[0] + ".thumbnail"
    if infile != outfile:
        try:
            im = Image.open(infile)
            im.thumbnail(size, Image.ANTIALIAS)
            im.save(outfile, "JPEG")
        except IOError:
            print "cannot create thumbnail for '%s'" % infile

다른 팁

이 스크립트는 PIL (Python Imaging Library)을 사용하여 이미지 (somepic.jpg)를 300 픽셀의 너비와 새로운 너비에 비례하여 크기를 조정합니다. 원래 너비의 300 픽셀 백분율 (IMG.Size [0])의 백분율을 결정한 다음 원래 높이 (IMG.Size [1])에 해당 백분율을 곱하여이를 수행합니다. 이미지의 기본 너비를 변경하려면 "Basewidth"를 다른 숫자로 변경하십시오.

from PIL import Image

basewidth = 300
img = Image.open('somepic.jpg')
wpercent = (basewidth/float(img.size[0]))
hsize = int((float(img.size[1])*float(wpercent)))
img = img.resize((basewidth,hsize), Image.ANTIALIAS)
img.save('sompic.jpg') 

또한 PIL의 썸네일 방법을 사용하는 것이 좋습니다. 모든 비율이 번거 로움을 제거하기 때문입니다.

그러나 중요한 힌트 중 하나 : 교체

im.thumbnail(size)

~와 함께

im.thumbnail(size,Image.ANTIALIAS)

기본적으로 PIL은 이미지를 사용하여 가장 성능이 좋지만 품질이 좋지 않은 결과를 조정하기 위해 가장 큰 필터를 사용합니다.

@Tomvon에 기반을 둔 다음과 같은 사용을 마쳤습니다.

너비 크기 조정 :

new_width  = 680
new_height = new_width * height / width 

크기 조정 :

new_height = 680
new_width  = new_height * width / height

그럼 그냥 :

img = img.resize((new_width, new_height), Image.ANTIALIAS)

Pil은 이미 이미지를자를 수있는 옵션이 있습니다

img = ImageOps.fit(img, size, Image.ANTIALIAS)
from PIL import Image

img = Image.open('/your iamge path/image.jpg') # image extension *.png,*.jpg
new_width  = 200
new_height = 300
img = img.resize((new_width, new_height), Image.ANTIALIAS)
img.save('output image name.png') # format may what u want ,*.png,*jpg,*.gif

동일한 종횡비를 유지하려고한다면 원래 크기의 비율로 크기를 조정하지 않습니까?

예를 들어, 원래 크기의 절반

half = 0.5
out = im.resize( [int(half * s) for s in im.size] )
from PIL import Image
from resizeimage import resizeimage

def resize_file(in_file, out_file, size):
    with open(in_file) as fd:
        image = resizeimage.resize_thumbnail(Image.open(fd), size)
    image.save(out_file)
    image.close()

resize_file('foo.tif', 'foo_small.jpg', (256, 256))

이 라이브러리를 사용합니다.

pip install python-resize-image

내 추악한 예.

함수 : "PIC [0-9A-Z]. [Extension], 120x120으로 크기를 조정하고 섹션을 중앙으로 이동하여 "ICO [0-9A-Z]. [Extension]으로 저장, 초상화로 작동합니다. 그리고 풍경 :

def imageResize(filepath):
    from PIL import Image
    file_dir=os.path.split(filepath)
    img = Image.open(filepath)

    if img.size[0] > img.size[1]:
        aspect = img.size[1]/120
        new_size = (img.size[0]/aspect, 120)
    else:
        aspect = img.size[0]/120
        new_size = (120, img.size[1]/aspect)
    img.resize(new_size).save(file_dir[0]+'/ico'+file_dir[1][3:])
    img = Image.open(file_dir[0]+'/ico'+file_dir[1][3:])

    if img.size[0] > img.size[1]:
        new_img = img.crop( (
            (((img.size[0])-120)/2),
            0,
            120+(((img.size[0])-120)/2),
            120
        ) )
    else:
        new_img = img.crop( (
            0,
            (((img.size[1])-120)/2),
            120,
            120+(((img.size[1])-120)/2)
        ) )

    new_img.save(file_dir[0]+'/ico'+file_dir[1][3:])

제한된 비율을 유지하고 최대 너비 / 높이를 통과하는 간단한 방법. 가장 예쁘지는 않지만 일을 끝내고 이해하기 쉽습니다.

def resize(img_path, max_px_size, output_folder):
    with Image.open(img_path) as img:
        width_0, height_0 = img.size
        out_f_name = os.path.split(img_path)[-1]
        out_f_path = os.path.join(output_folder, out_f_name)

        if max((width_0, height_0)) <= max_px_size:
            print('writing {} to disk (no change from original)'.format(out_f_path))
            img.save(out_f_path)
            return

        if width_0 > height_0:
            wpercent = max_px_size / float(width_0)
            hsize = int(float(height_0) * float(wpercent))
            img = img.resize((max_px_size, hsize), Image.ANTIALIAS)
            print('writing {} to disk'.format(out_f_path))
            img.save(out_f_path)
            return

        if width_0 < height_0:
            hpercent = max_px_size / float(height_0)
            wsize = int(float(width_0) * float(hpercent))
            img = img.resize((max_px_size, wsize), Image.ANTIALIAS)
            print('writing {} to disk'.format(out_f_path))
            img.save(out_f_path)
            return

여기에 있습니다 파이썬 스크립트 이 기능을 사용하여 배치 이미지 크기 조정을 실행합니다.

슬라이드 쇼 비디오의 일부 이미지를 크기를 조정하려고했는데 그로 인해 최대 치수가 하나뿐만 아니라 최대 너비를 원했습니다. 그리고 최대 높이 (비디오 프레임의 크기).
그리고 항상 초상화 비디오의 가능성이있었습니다 ...
그만큼 Image.thumbnail 방법은 유망했지만 작은 이미지로 고급 스케일로 만들 수는 없었습니다.

그래서 여기서 (또는 다른 장소에서) 그렇게 할 수있는 명백한 방법을 찾을 수 없었을 때, 나는이 기능을 썼고 앞으로 나아갈 수 있도록 여기에 넣었습니다.

from PIL import Image

def get_resized_img(img_path, video_size):
    img = Image.open(img_path)
    width, height = video_size  # these are the MAX dimensions
    video_ratio = width / height
    img_ratio = img.size[0] / img.size[1]
    if video_ratio >= 1:  # the video is wide
        if img_ratio <= video_ratio:  # image is not wide enough
            width_new = int(height * img_ratio)
            size_new = width_new, height
        else:  # image is wider than video
            height_new = int(width / img_ratio)
            size_new = width, height_new
    else:  # the video is tall
        if img_ratio >= video_ratio:  # image is not tall enough
            height_new = int(width / img_ratio)
            size_new = width, height_new
        else:  # image is taller than video
            width_new = int(height * img_ratio)
            size_new = width_new, height
    return img.resize(size_new, resample=Image.LANCZOS)

베개로 이미지를 열 필요가 없거나 원하지 않는 경우 다음을 사용하십시오.

from PIL import Image

new_img_arr = numpy.array(Image.fromarray(img_arr).resize((new_width, new_height), Image.ANTIALIAS))

나는 그런 식으로 이미지를 크기를 조정했고 아주 잘 작동합니다.

from io import BytesIO
from django.core.files.uploadedfile import InMemoryUploadedFile
import os, sys
from PIL import Image


def imageResize(image):
    outputIoStream = BytesIO()
    imageTemproaryResized = imageTemproary.resize( (1920,1080), Image.ANTIALIAS) 
    imageTemproaryResized.save(outputIoStream , format='PNG', quality='10') 
    outputIoStream.seek(0)
    uploadedImage = InMemoryUploadedFile(outputIoStream,'ImageField', "%s.jpg" % image.name.split('.')[0], 'image/jpeg', sys.getsizeof(outputIoStream), None)

    ## For upload local folder
    fs = FileSystemStorage()
    filename = fs.save(uploadedImage.name, uploadedImage)

더 현대적인 래퍼 로이 질문을 업데이트하는 것만 으로이 도서관은 베개를 감싸십시오 (Pil의 포크)https://pypi.org/project/python-resize-image/

다음과 같은 일을 할 수 있습니다 :-

from PIL import Image
from resizeimage import resizeimage

fd_img = open('test-image.jpeg', 'r')
img = Image.open(fd_img)
img = resizeimage.resize_width(img, 200)
img.save('test-image-width.jpeg', img.format)
fd_img.close()

위의 링크에서 더 많은 예제를 힙.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top