【问题标题】:Python flask ajax save decoded base64 image to server temporarilyPython烧瓶ajax将解码的base64图像临时保存到服务器
【发布时间】:2023-03-14 23:46:01
【问题描述】:

在将图像发送到我的烧瓶应用程序之前,我正在客户端调整图像大小。

已调整大小的图像被绘制到要调整大小的画布中,通过 POST 请求发送。

在我的应用中,图像是通过 base64 解码的:

def resize_image(item):
    content = item.split(';')[1]
    image_encoded = content.split(',')[1]
    body = base64.decodestring(image_encoded.encode('utf-8'))
    return body

图像数据以type String 的形式存储在body 变量中。我可以将数据保存到我的本地机器并且它可以工作:

filename = 'some_image.jpg' 
with open(filename, 'wb') as f:
    print "written"
    f.write(body)

我需要将调整大小的图像上传到 AWS3。有一点我需要read() 图像内容,但是直到图像作为文件保存在某个地方它仍然是一个字符串,所以它失败了:

file_data = request.values['a']
imagedata = resize_image(file_data)              

s3 = boto.connect_s3(app.config['MY_AWS_ID'], app.config['MY_AWS_SECRET'], host='s3.eu-central-1.amazonaws.com')

bucket_name = 'my_bucket'
bucket = s3.get_bucket(bucket_name)
k = Key(bucket)  

# fails here         
file_contents = imagedata.read()

k.key = "my_images/" + "test.png"

k.set_contents_from_string(file_contents)

除非有其他解决方案,否则我想我将图像临时保存到我的服务器(Heroku)并上传然后删除它,这将如何工作?事后删除在这里很重要!

【问题讨论】:

    标签: python ajax image


    【解决方案1】:

    set_contents_from_string 将字符串作为参数,您可能只需将图像字符串数据直接传递给它以上传到 S3

    解决方案:

    删除这部分:

    file_contents = imagedata.read()
    

    在这里直接使用imagedata

    k.set_contents_from_string(imagedata)
    

    【讨论】:

      【解决方案2】:

      如果您需要对数据调用 .read(),但不需要在磁盘上保存文件,请使用 StringIO:

      import StringIO
      output = StringIO.StringIO()
      output.write('decoded image')
      output.seek(0)
      
      
      output.read()
      Out[1]: 'decoded image'
      

      【讨论】:

        猜你喜欢
        • 2018-06-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-18
        • 1970-01-01
        • 2013-02-13
        • 1970-01-01
        • 2014-06-04
        相关资源
        最近更新 更多