小编Fab*_*yra的帖子

在 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)
Run Code Online (Sandbox Code Playgroud)

python django python-imaging-library python-3.x google-cloud-platform

6
推荐指数
1
解决办法
2173
查看次数