【问题标题】:How to upload an image from web into Google Cloud Storage?如何将网络上的图片上传到 Google Cloud Storage?
【发布时间】:2015-02-21 18:28:34
【问题描述】:

我正在开发一个新闻应用程序,并希望将新闻图片缓存在我自己的谷歌云存储中。

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

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

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

【问题讨论】:

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


    【解决方案1】:

    试试这个:

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

    【讨论】:

    • 非常感谢。 1) 我认为您不再需要image = images.Image(image_bytes)。 2)代码看起来很有前途,但它不起作用。你试过了吗?
    • 是的,它确实有效。我将它与我的 Flask 应用程序一起使用。确保您授予 GAE 应用程序写入您的存储桶的权限:developers.google.com/appengine/docs/python/googlestorage/… 我添加了一条关于我为什么使用图像转换的评论
    • 现在可以使用了。非常感谢您的帮助。调整图像大小的好主意。我想有这样的要求意味着,我不能使用 BlobStorage 并且必须坚持使用 Cloud Storage,因为不推荐使用前者的文件写入。谢谢
    猜你喜欢
    • 1970-01-01
    • 2020-04-08
    • 2014-10-10
    • 2017-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-20
    • 2020-07-26
    相关资源
    最近更新 更多