这就是我需要的:当用户上传图像时,验证该图像是否超过某个尺寸,如果是这样,则更改尺寸。此代码没有错误,但保存的图像大小没有变化。该图片位于Google云端存储分区中,之前上传,但工作正常。欢迎任何想法。提前致谢。
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)
你在这里发生了很多额外的事情,包括将图像保存到本地文件系统,这是不必要的。这个最小的例子应该有效:
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
im = Image.frombytes(blob=bucket.get_blob(data['name']).download_as_string())
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())
这是我试过的,它复制文件,但没有调整大小:
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')
fp = io.BytesIO(Blob(image_path, bucket).download_as_string())
im = Image.open(fp)
x, y = im.size
if x>450 or y>450:
thumbnail_blob = bucket.blob('new_file.jpg')
im.thumbnail((450,450))
im.save(fp, "JPEG")
thumbnail_blob.upload_from_string(fp.getvalue(), content_type="image/jpeg")