How to upload an image from web into Google Cloud Storage?(如何将网络上的图片上传到 Google Cloud Storage?)
问题描述
我正在开发一个新闻应用程序,并希望将新闻图片缓存在我自己的谷歌云存储中.
I am working on a news app and would like to cache the news images on my own google cloud storage.
我打算在 GAE 上使用 Flask.我发现的所有示例都与将文件从用户浏览器上传到云存储有关.
I am planning to use Flask on GAE. All examples I have found relate to upload a file from user's browser into cloud storage.
通过 url 获取图像并将其上传到谷歌云存储的最佳方法是什么?我希望这是有道理的,请随时提出改进建议.非常感谢
What is the best way to obtain an image via an url and upload it to google cloud storage? I hope this makes sense, please feel free to suggest improvements. Many Thanks
def main():
bucket_name = os.environ.get('BUCKET_NAME',
app_identity.get_default_gcs_bucket_name())
bucket = '/' + bucket_name
filename = bucket + '/image_name'
image_url = "http://news.com/crash.jpg"
try:
create_file(image_url, filename)
except Exception, e:
logging.exception(e)
return "Success", 201
def create_file(image_url, filename):
image = cStringIO.StringIO(urllib.urlopen(image_url).read()) // Not sure about this
img = Image.open(image)
write_retry_params = gcs.RetryParams(backoff_factor=1.1)
gcs_file = gcs.open(filename,
'w',
content_type='image/jpeg', // ???? Is MIME type correct?
options={'x-goog-acl': 'public'},
retry_params=write_retry_params)
gcs_file.write(img)
gcs_file.close()
推荐答案
试试这个:
import urllib2
from google.appengine.api import images
import cloudstorage as gcs
image_at_url = urllib2.urlopen(url)
content_type = image_at_url.headers['Content-Type']
filename = #use your own or get from file
image_bytes = image_at_url.read()
image_at_url.close()
image = images.Image(image_bytes)
# this comes in handy if you want to resize images:
if image.width > 800 or image.height > 800:
image_bytes = images.resize(image_bytes, 800, 800)
options={'x-goog-acl': 'public-read', 'Cache-Control': 'private, max-age=0, no-transform'}
with gcs.open(filename, 'w', content_type=content_type, options=options) as f:
f.write(image_bytes)
f.close()
这篇关于如何将网络上的图片上传到 Google Cloud Storage?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将网络上的图片上传到 Google Cloud Storage?
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
- 沿轴计算直方图 2022-01-01
- 如何将一个类的函数分成多个文件? 2022-01-01
- python-m http.server 443--使用SSL? 2022-01-01
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- padding='same' 转换为 PyTorch padding=# 2022-01-01
- pytorch 中的自适应池是如何工作的? 2022-07-12
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01