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

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

有人帮忙吗?

158827 次浏览

这应该会奏效:

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')的方法去快乐。

您还需要检测图像的 imimetype/扩展,因为您可以正确地保存它,在一个简短的示例中,您可以使用下面的代码进行 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()

然后,根据需要使用保存的文件。

很简单,非常简单

将 base64 _ string 转换为 opencv (RGB) :

from PIL import Image
import cv2


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

您可以尝试使用 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');