问题描述
我正在尝试使用 python 创建一个图像缩略图创建函数,在谷歌云平台的函数中运行。图像作为 base64 字符串发送到云函数,使用 Python 的 Pillow 包进行操作和缩小。然后将其作为图像上传,从 Pillow Image 对象到 BytesIO 对象,然后保存到谷歌云存储。一切顺利。
这里的问题很奇怪:在手动创建访问令牌之前,Google Cloud Storage 无法识别图像。否则,图片会无限循环,永远无法加载,永远无法使用。
我已经查看了 this SO post,它有一个与我非常相似的问题(这里的图像正好显示了我的问题:无法正确加载上传的文件),但它在两个重要类别中有所不同:1)它们是直接操作图像数组,而我的代码从未触及它,并且 2) 它们在 Node.js 中工作,其中 Firebase SDK 与 Python 不同。
def thumbnailCreator(request):
# Setting up the resourcse we are going to use
storage_client = storage.Client()
stor_bucket = storage_client.bucket(BUCKET_LINK)
# Retriving the Data
sent_data = request.get_json()['data']
name = sent_data['name']
userID = sent_data['userID']
# Process to go between base64 string to bytes,to a file object
imageString = stor_bucket.blob(PATH_TO_FULL_SIZE_IMAGE).download_as_string()
imageFile = BytesIO(imageString)
image = Image.open(imageFile)
# Resizing the image is the goal
image = image.resize(THUMBNAIL_SIZE)
# Go between pillow Image object to a file
imageFile = BytesIO()
image.save(imageFile,format='PNG')
imageBytes = imageFile.getvalue()
image64 = base64.b64encode(imageBytes)
imageFile.seek(0)
# Uploading the Data
other_blob = stor_bucket.blob(PATH_FOR_THUMBNAIL_IMAGE)
other_blob.upload_from_file(imageFile,content_type = 'image/png')
return {'data': {'response': 'ok','status': 200}}
再次,这有效。我感觉 MIME 类型有问题。在这种类型的编程/网络/图像处理方面,我是新手,所以我一直在寻找更好的方法来做到这一点。无论如何,感谢您的任何帮助。
解决方法
看来这个问题的前提 - 必须手动制作访问令牌才能使图像工作 - 不准确。经过进一步测试,错误来自我正在使用的代码库的其他部分。上面的 python 脚本确实适用于图像处理。可以通过代码生成图像的访问令牌,并在客户端提供。
如果有人在将来需要在 Google Cloud Platform 中使用 Pillow/PIL 时偶然发现它,请留下它。