我想將影像上傳到 Google 存盤桶,但是我想在上傳之前減小影像的大小。當我不呼叫 self._resize_image 方法時,影像會成功上傳,沒有任何問題。但是,當我呼叫 resize 方法時,它會一直作業到 image.tobytes() 方法。呼叫 image.tobytes() 方法后,影像似乎已損壞。我嘗試手動除錯并在谷歌上搜索 tobytes 方法,但到目前為止還沒有找到任何東西。您是否知道導致影像損壞的原因,或者是否有替代方法來縮放影像?
def _resize_image(self, image: bytes, base_with: int = 300) -> bytes:
stream = BytesIO(image)
image = Image.open(stream).convert("RGBA")
width_percentage = base_with / float(image.size[0])
height_size = int(float(image.size[1]) * float(width_percentage))
image = image.resize((base_with, height_size), Image.ANTIALIAS)
# if I do image.show() here the picture is still displayed correctly.
return image.tobytes() # after this line the picture is getting uploaded, but can't be read by Google anymore.
def upload_image_to_bucket(self, image: bytes, bucket_folder: str, compress: bool = True) -> str:
if compress:
# if I don't call this method the picture get's uploaded correctly.
image = self._resize_image(image=image)
file_name = f"{UUIDService().create_uuid(length=40)}.jpeg"
bucket = self._client.storage.bucket()
blob = bucket.blob(f"{bucket_folder}/{file_name}")
blob.upload_from_string(data=image, content_type="image/jpeg")
return file_name
uj5u.com熱心網友回復:
來自Pillow 的檔案tobytes:
此方法從內部存盤回傳原始影像資料。對于壓縮影像資料(例如 PNG、JPEG),請使用 save(),并為記憶體中的資料使用 BytesIO 引數。
因此該tobytes()方法回傳 Pillow 對影像的內部表示,大概是用frombytes(). 如果要將影像保存為 JPEG,請使用檔案建議的save()方法:
output = BytesIO()
image.save(output, format="jpeg")
... # do something with `output`
uj5u.com熱心網友回復:
這是因為 tobytes() 函式給出了原始的未壓縮位元組。您將使用 PIL 的保存功能將其保存到緩沖區中,然后上傳。
output = io.BytesIO()
img.save(output, format='JPEG')
uj5u.com熱心網友回復:
它可能是 Image.ANTIALIAS 函式;嘗試將該欄位留空。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/481631.html
下一篇:更改訓練集中的所有影像
