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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16214190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:02:11  来源:igfitidea点击:

How to convert base64 string to image?

pythonbase64

提问by omarsafwany

I'm converting an image to base64string and sending it from android device to the server. Now, I need to change that string back to an image and save it in the database.

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

Any help?

有什么帮助吗?

采纳答案by rmunn

Try this:

尝试这个:

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

回答by pypat

This should do the trick:

这应该可以解决问题:

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

回答by Fernando Mota

Just use the method .decode('base64')and go to be happy.

只需使用该方法.decode('base64')并获得快乐。

You need, too, to detect the mimetype/extension of the image, as you can save it correctly, in a brief example, you can use the code below for a django view:

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

And, after this, use the file saved as you want.

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

Simple. Very simple. ;)

简单的。很简单。;)

回答by Jumabek Alikhanov

Return converted image without saving:

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

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)

回答by Anthony Anyanwu

You can try using open-cv to save the file since it helps with image type conversions internally. The sample code:

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

Then somewhere in your code you can use it like this:

然后在您的代码中的某个地方,您可以像这样使用它:

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