Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/image-processing/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将base64字符串转换为图像?_Python_Base64 - Fatal编程技术网

Python 如何将base64字符串转换为图像?

Python 如何将base64字符串转换为图像?,python,base64,Python,Base64,我正在将图像转换为base64字符串,并将其从android设备发送到服务器。现在,我需要将该字符串更改回图像,并将其保存在数据库中 有什么帮助吗?这应该可以做到: image = open("image.png", "wb") image.write(base64string.decode('base64')) image.close() 试试这个: import base64 imgdata = base64.b64decode(imgstring) filename = 'some_im

我正在将图像转换为base64字符串,并将其从android设备发送到服务器。现在,我需要将该字符串更改回图像,并将其保存在数据库中


有什么帮助吗?

这应该可以做到:

image = open("image.png", "wb")
image.write(base64string.decode('base64'))
image.close()
试试这个:

import base64
imgdata = base64.b64decode(imgstring)
filename = 'some_image.jpg'  # I assume you have a way of picking unique filenames
with open(filename, 'wb') as f:
    f.write(imgdata)
# f gets closed when you exit the with statement
# Now save the value of filename to your database

只要使用
.decode('base64')
方法,就可以快乐了

您还需要检测图像的mimetype/扩展名,因为您可以正确保存它。在一个简单的示例中,您可以使用下面的代码创建django视图:

def receive_image(req):
    image_filename = req.REQUEST["image_filename"] # A field from the Android device
    image_data = req.REQUEST["image_data"].decode("base64") # The data image
    handler = open(image_filename, "wb+")
    handler.write(image_data)
    handler.close()
然后,使用保存为所需的文件


简单。很简单

返回转换后的图像而不保存:

from PIL import Image
import cv2

# Take in base64 string and return cv image
def stringToRGB(base64_string):
    imgdata = base64.b64decode(str(base64_string))
    image = Image.open(io.BytesIO(imgdata))
    return cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB)

您可以尝试使用open cv保存文件,因为它有助于在内部进行图像类型转换。示例代码:

import cv2
import numpy as np

def save(encoded_data, filename):
    nparr = np.fromstring(encoded_data.decode('base64'), np.uint8)
    img = cv2.imdecode(nparr, cv2.IMREAD_ANYCOLOR)
    return cv2.imwrite(filename, img)
然后在代码中的某个地方,您可以这样使用它:

save(base_64_string, 'testfile.png');
save(base_64_string, 'testfile.jpg');
save(base_64_string, 'testfile.bmp');

@rmunn…wb代表什么@omarsafwany它的意思是“w”和“b”,这为我创建了一个损坏的图像。@JoshUsre-如果你从这个示例代码中得到了一个损坏的图像,可能是因为你解码的base64数据不是有效的JPEG。它可能是一种不同类型的图像——例如PNG或GIF图像——而找出您拥有的图像类型超出了本答案的范围。但是试着为你拥有的图像类型创建一个扩展名正确的文件,看看是否有效。如果你仍然有困难,问一个真正的问题,而不是在一篇两年前的帖子上发表一句话的评论。一个真正的问题会得到更多的关注和更好的答案。@JumabekAlikhanov-你应该问一个新问题。在我的答案中添加评论只会通知一个人(我),但一个新问题将被成千上万的人看到,他们可能比我更了解opencv。从我所看到的opencv文档来看,我只知道如何从文件中打开图像,因此您的“不保存到任何文件”需要其他人回答。因此,请提出一个新问题,并提供足够的细节,希望有人知道如何做你想做的事情。@AbhishekSharma链接只鼓励评论,因为内容可能会改变或消失。请添加您的方法作为下次的答案。我使用了此方法。我喜欢它,因为它几乎是最简单的,最接近我想要的结果——基本上就是将字符串转换成磁盘上的图像文件。