python - 在 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)
解决方案
这里发生了很多额外的事情,包括将图像保存到本地文件系统,这是不必要的。这个最小的例子应该可以工作:
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())
推荐阅读
- javascript - 在对象中的Javascript函数中传递参数
- python - OpenGL 光 - 颜色不会在一个角度平滑变化
- python-3.x - python main.py 在pycharm中转文本文件
- asp.net-core - 如何使用 Moq 模拟和期望具有 Action 委托作为参数之一的方法
- javascript - 此关键字的分配
- ios - 从 swift 访问前向声明的枚举的属性
- javascript - javascript/reactjs中具有多个参数的递归函数
- c# - FontStyle 枚举与 CheckBox.Text FontStyles 的可用 FontStyles 之间的差异
- php - Laravel 查询错误 - 调用未定义的方法 Illuminate\Database\Query\Builder::query()
- arrays - React Native:如何使用 onPress 函数从 url 数组中打开特定的 URL?