使用此代碼中的想法在回圈中動態更改影像大小,這里有一點問題。有幾種方法可以獲取以位元組為單位的影像大小,只有一種方法可以提供準確的結果,但這需要將檔案保存在磁盤中。如果我每次都保存磁盤并再次讀取它,那么每次迭代都會花費雙倍的努力。有什么方法可以準確讀取影像結果?
from PIL import Image
import os
import sys
image = Image.open(image_path
size_kb = os.stat(image_path).st_size
buffer = BytesIO()
image.save(buffer, format="jpeg", quality = 100, optimize = True) # Does not save but acts like an image saved to disc
size_kb2 = (buffer.getbuffer().nbytes)
列印 3 個不同的結果print(size_kb, size_kb2, sys.getsizeof(image.tobytes()),)給我 3 個不同的結果,相同的影像os.stat給出了準確的結果(與 Linux 作業系統顯示的結果相同)
我不想將影像保存到光碟以再次讀取它,因為這會花費很多時間
整個代碼:
STEP = 32
MIN_SIZE = 32
def resize_under_kb(image:Image,size_kb: float, desired_size:float)-> Image:
'''
Resize the image under given size in KB
args:
Image: Pil Image object
size_kb: Current size of image in kb
desired_size: Final desired size asked by user
'''
size = image.size
new_width_height = max(size) - STEP # Decrease the pixels for first pass
while new_width_height > MIN_SIZE and size_kb > desired_size: # either the image reaches minimun dimension possible or the desired possible size
image = image.resize((new_width_height,new_width_height)) # keep on resizing until you get to desired output
buffer = BytesIO()
image.save(buffer, format="jpeg", quality = 100, optimize = True) # Does not save but acts like an image saved to disc
size_kb = buffer.getbuffer().nbytes
size = image.size # Current resized pixels
new_width_height = max(size) - STEP # Dimensions for next iteration
return image
uj5u.com熱心網友回復:
這段代碼:
size_kb = os.stat(image_path).st_size
列印現有 JPEG 在磁盤上占用的位元組數。
這段代碼:
buffer = BytesIO()
image.save(buffer, format="jpeg", quality = 100, optimize = True) # Does not save but acts like an image saved to disc
size_kb2 = (buffer.getbuffer().nbytes)
列印影像保存在磁盤上的位元組數......由 PIL 當前的 JPEG 編碼器,具有自己的 Huffman 表和質量和色度子采樣,并且不允許檔案系統最小塊大小。
這可能與您最初從磁盤讀取的大小有很大不同,因為這可能是由不同的軟體創建的,速度和質量的權衡不同。它甚至可能在兩個版本的 PIL 之間有所不同。
這段代碼:
len(image.tobytes())
告訴您影像當前在記憶體中解壓縮時占用的位元組數,不考慮它所需的其他資料結構,也不考慮元資料(評論、GPS 資料、著作權、制造商鏡頭資料和設定資料)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/462336.html
上一篇:具有11個元素的框函式
