Fab*_*yra 6 python django python-imaging-library python-3.x google-cloud-platform
这就是我需要的:当用户上传图像时,验证该图像是否超过某个大小,如果是,则更改大小。此代码没有错误,但保存的图像大小不变。该图像位于 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)
这里发生了很多额外的事情,包括将图像保存到本地文件系统,这是不必要的。这个最小的例子应该可以工作:
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())
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2173 次 |
| 最近记录: |