this short post에서 Mike Fletcher와 effbot은 여러분이하고 싶은 작업에 대한 훌륭한 접근 방식을 보여줍니다.
편집 :: 10K 요구 사항은 이미지의 형식에 따라 이미지가 얼마나 잘 압축 될지 예측하기 어렵습니다. 압축 알고리즘이 너무 미세하기 때문에 어렵습니다. 섬네일 크기가 < 10K 요구 사항을 준수하면서 가능한 한 큰 픽셀 (픽셀 단위)로 표시되도록하려면 '시행 착오'방식을 사용하여 크기 조정 계수에 대해보다 세련된 추측을해야 할 수도 있습니다. 수용 가능한 결과.
예를 들어, 여기 ... 무슨 일이 일어나고 있는지 설명하기 위해 충분한 print 문으로 (! 아니라 더 나은 전략이있을 수 있습니다) & C를 정확한 크기를 얻기에 "이진 검색"접근 방식 :
import Image
import cStringIO
import math
import os
import stat
# try no more than 10 times, then give up
MAX_TRIES = 10
def getThumbnail(filename, max_bytes=(10*1024)):
'''Get a thumbnail image of filename, <max_bytes'''
original_size = os.stat(filename)[stat.ST_SIZE]
print "Original file size: %.1f KB" % (original_size/1024.)
image = Image.open(filename)
image.load()
print "Original image size: %dx%d pixels" % image.size
min_bytes = int(0.9 * max_bytes)
largest_side = max(image.size)
smallest_side = 16
for attempt in range(MAX_TRIES):
try_side = (largest_side + smallest_side)/2
print "Attempt #%d of %d" % (attempt+1, MAX_TRIES)
print "Side must be within [%d:%d], now trying %d" % (
smallest_side, largest_side, try_side)
thumb = image.copy()
thumb.thumbnail((try_side,try_side), Image.ANTIALIAS)
afile = cStringIO.StringIO()
thumb.save(afile, "PNG")
resulting_size = len(afile.getvalue())
afile.close()
print "Reduced file size: %.1f KB" % (resulting_size/1024.)
print "Reduced image size: %dx%d pixels" % thumb.size
if min_bytes <= resulting_size <= max_bytes:
print "Success!"
return thumb
elif resulting_size > max_bytes:
print "Too large (>%d), reducing more" % max_bytes
largest_side = try_side
else:
print "Too small (<%d), reducing less" % min_bytes
smallest_side = try_side
print "too many attempts, returning what I've got!"
return thumb
def main():
thumb = getThumbnail("pyth.png")
print "Reduced image size: %dx%d pixels" % thumb.size
print "Saving to thumb.png"
thumb.save("thumb.png")
thumb_size = os.stat("thumb.png")[stat.ST_SIZE]
print "Reduced file size: %.1f KB" % (thumb_size/1024.)
print "Done, bye!"
if __name__ == '__main__':
main()
중복 : http://stackoverflow.com/questions/273946/how-do-i-resize-an-image-using-pil-and-maintain-its-aspect-ratio –
이것은 중복이 아닙니다! "EDIT"에서 지금 말했듯이, 비례 적으로 이미지의 크기를 조정할뿐만 아니라 크기가 10KB보다 작은 지 확인해야하는 기능이 필요합니다. – quilby