Python 在 html 上传后以 base 64 对图像进行编码

Python encode an image in base 64 after a html upload

我的页面中有上传图片的输入。 当您单击 "send image" 时,我的后端会收到 post 请求。

我没有,也不想保存图像。

从后面看,我所做的是:我将图像发送到 API,它会 return 给我图像的标签,然后我将显示标签和图像本身,即已上传,在我的html页面。

if request.method == "POST":
            form = ImageForm(request.POST, request.FILES)

            if form.is_valid():
                imageUploaded = request.FILES['image_file']
                try:
                    c = Client(cId, sId)
                    c.get_token()
                    tags = c.image_lookup(imageUploaded)

                    urlImage = base64.b64encode(imageUploaded.read())
                    context.update({
                        'image_path': urlImage,
                        'tags': tags.json,
                        'btn_visible': True,
                    })
                except ValueError as e:
                    logging.info(e)
                    context.update({
                        'btn_visible': False,
                        'error_message': 'A problem occured, we will fix it as soon as possible. We apologise for the inconvenience.'
                    })

在我的 HTML:

<img id="cv-image" src="data:image/png;base64,{{ image_path }}">

但是,我的问题是我的 image_path 非常空。

有什么问题?

编辑: 这太奇怪了,如果我注释调用客户端 class 的代码,该代码在 API 上执行 GET 和 POST,它将起作用。我仍然不明白,也不知道如何让它发挥作用。

好的,因为我没有保存图像,一旦我将它发送到 API,对象本身就不再可用了。

不确定为什么我仍然可以打印它,我不得不复制它:

if form.is_valid():
            imageUploaded = request.FILES['image_file']
            imageCopy = copy.deepcopy(imageUploaded)
            try:
                c = Client(cId, sId)
                c.get_token()
                tags = c.image_lookup(imageUploaded)

                urlImage = base64.b64encode(imageCopy.read())

现在一切正常!

如问,这里是Image_lookup的代码:

def image_lookup(self, imageUploaded, image_type=None):
        '''POST /v1/imageLookup'''
        param_files = [
            ('input_image', ('image.jpg', imageUploaded, image_type or 'image/png'))
        ]

        return self.post('someAPIurl/imageLookup', files=param_files)

我可能来不及参加这里的派对了,但我只是偶然发现了这个,在我看来这像是文件搜索位置的问题。如果image_lookup()读取文件(或导致文件被读取),它可能会在文件末尾留下查找位置。随后(从该位置)读取文件,因此 return 没有。

这是有道理的,因为注释掉 image_lookup() 调用,并在调用之前制作文件实例的副本,两者都有效。如果确实如此,则只需将文件返回到开头即可,这很简单:file.seek(0).

这是未经测试的,但应该是您所需要的:

c = Client(cId, sId)
c.get_token()
tags = c.image_lookup(imageUploaded)

# Seek file back to the beginning
imageUploaded.seek(0)

urlImage = base64.b64encode(imageUploaded.read())