Google App Engine Base64对blobstore中的图像进行编码

时间:2014-03-03 07:22:33

标签: google-app-engine base64 blobstore

我正在制作一个可以接受用户上传图片并将其转换为base64的webapp。

class TestImageHandler(blobstore_handlers.BlobstoreUploadHandler):
    def post(self):

    upload_files = self.get_uploads('file')  # 'file' is file upload field in the form
    if upload_files:
        blob_info = upload_files[0]
        process_img(blob_info)
        blobstore.delete(blob_info.key())  # optional: delete file after import

我计划在process_img过程中处理图像,但却发现我不知道如何从blobstore中检索图像数据并对其进行编码。

2 个答案:

答案 0 :(得分:0)

class TestImageHandler(blobstore_handlers.BlobstoreUploadHandler):
    def post(self):

        upload_files = self.get_uploads('file')  # 'file' is file upload field in the form
        if upload_files:
            blob_info = upload_files[0]
            string = process_img(blob_info)
            blobstore.delete(blob_info.key())  # optional: delete file after import

            self.response.out.write('<img alt = "" src = "%s" >' % string)


def process_img(blob_info):
    blob_reader = blobstore.BlobReader(blob_info.key())
    data = blob_reader.read()
    return "data:image/%s;base64,"%blob_info.filename.split('.')[1]+base64.b64encode(data)

答案 1 :(得分:0)

class TestImageHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):

    upload_files = self.get_uploads('file')
    data_to_64 = re.search(r'base64,(.*)', upload_files).group(1)
    decoded = data_to_64.decode('base64')
    file_name = files.blobstore.create(mime_type='image/png')
    with files.open(file_name, 'a') as f:
       f.write(decoded)
    files.finalize(file_name)
    blob_key = files.blobstore.get_blob_key(file_name)