如何将图像从网络上传到Google云端存储?

时间:2014-12-23 15:26:45

标签: python google-app-engine flask google-cloud-storage

我正在制作新闻应用,并希望将新闻图片缓存在我自己的Google云存储中。

我打算在GAE上使用Flask。我发现的所有示例都涉及将用户浏览器中的文件上传到云存储中。

通过网址获取图片并将其上传到Google云端存储的最佳方式是什么? 我希望这是有道理的,请随时提出改进建议。非常感谢

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()

1 个答案:

答案 0 :(得分:4)

试试这个:

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()