首页 > 解决方案 > 在 Google Cloud Storage Bucket 中使用 PIL 更改图像大小(来自 GCloud 中的 VM)

问题描述

这就是我需要的:当用户上传图片时,验证该图片是否超过了某个大小,如果是,请更改大小。此代码没有错误,但保存的图像大小没有变化。该图像位于 Google Cloud Storage Bucket 中,之前已上传,但效果很好。欢迎任何想法。提前致谢。

from PIL import Image
from django.core.files.storage import default_storage
from google.cloud import storage
from google.cloud.storage import Blob
import io

if default_storage.exists(image_path):
    client = storage.Client()
    bucket = client.get_bucket('mybucket.appspot.com')
    blob = Blob(image_path, bucket)
    contenido = blob.download_as_string()
    fp = io.BytesIO(contenido)
    im = Image.open(fp)
    x, y = im.size
    if x>450 or y>450:
        im.thumbnail((450,450))
        im.save(fp, "JPEG")
        # im.show() here it shows the image thumbnail (thumbnail works)
        blob.upload_from_string(fp.getvalue(), content_type="image/jpeg")
        blob_dest = Blob('new_image.jpg', bucket)
        blob.download_as_string()
        blob_dest.rewrite(blob)

标签: pythondjangopython-3.xgoogle-cloud-platformpython-imaging-library

解决方案


这里发生了很多额外的事情,包括将图像保存到本地文件系统,这是不必要的。这个最小的例子应该可以工作:

import io 

from PIL import Image
from django.core.files.storage import default_storage
from google.cloud import storage

if default_storage.exists(image_path):
    client = storage.Client()
    bucket = client.get_bucket('mybucket.appspot.com')

    # Download the image
    blob = bucket.get_blob(data['name']).download_as_string()
    bytes = io.BytesIO(blob)
    im = Image.open(bytes)

    x, y = im.size

    if x>450 or y>450:
        # Upload the new image
        thumbnail_blob = bucket.blob('new_image.jpg')
        thumbnail_blob.upload_from_string(im.resize(450, 450).tobytes())

推荐阅读