如何在不保存的情况下将Image PIL转换为Base64

时间:2018-01-12 15:31:19

标签: python image base64 pillow

我使用Python生成图像,我需要将此Pil图像转换为Base64,而不将其保存到任何文件夹中...

我有一些数据,我通过下面的行获得RGB img:

img = Image.fromarray(data,'RGB')

将此PIL转换为base64的简单方法是什么?(我无法打开文件图像,因为我不能保存img)?

感谢您的帮助

使用Node JS,我可以使用以下行获得正确的base64:

pythonShell= require("python-shell");

app.post('/index/gen/',urlencodedParser, function (req,res){ 
  pythonShell.run('minigen.py', function (err, results) {
  if (err) throw err; 
  var img = base64img.base64Sync('./images/miniature.jpg');
  res.send(img); }); 
}) 

但如果我使用NodeJS,我必须保存文件......

这是从图像生成矩阵的代码,您不需要知道数据中的内容;)

image = Image.open("./carte/"+fichier)              
image = image.resize((400,400),Image.ANTIALIAS)     
w,h = image.size                                    
tab = numpy.array(image)                            
data = numpy.zeros((h, w, 3), dtype=numpy.uint8)

4 个答案:

答案 0 :(得分:3)

您可以像这样使用base64库:

import base64

base64.b64encode(img.tobytes())

请参阅Image对象的tobytes()方法。

答案 1 :(得分:3)

我找到了解决方案。希望这有帮助!

img = Image.fromarray(data, 'RGB')                  #Crée une image à partir de la matrice
buffer = BytesIO()
img.save(buffer,format="JPEG")                  #Enregistre l'image dans le buffer
myimage = buffer.getvalue()                     
print "data:image/jpeg;base64,"+base64.b64encode(myimage)

答案 2 :(得分:3)

@florian的回答对我有很大帮助,但是base64.b64encode(img_byte)返回了字节,因此我需要在连接之前将其解码为字符串(使用python 3.6):

def img_to_base64_str(self, img):
    buffered = BytesIO()
    img.save(buffered, format="PNG")
    buffered.seek(0)
    img_byte = buffered.getvalue()
    img_str = "data:image/png;base64," + base64.b64encode(img_byte).decode()

答案 3 :(得分:0)

或者您可以使用类似这样的内容:

import glob
import random
import base64

from PIL import Image
from io import BytesIO
import io


def get_thumbnail(path):
    path = "\\\\?\\"+path # This "\\\\?\\" is used to prevent problems with long Windows paths
    i = Image.open(path)    
    return i

def image_base64(im):
    if isinstance(im, str):
        im = get_thumbnail(im)
    with BytesIO() as buffer:
        im.save(buffer, 'jpeg')
        return base64.b64encode(buffer.getvalue()).decode()

def image_formatter(im):
    return f'<img src="data:image/jpeg;base64,{image_base64(im)}">'

只需通过get_thumbnail函数和image_formatter中的图像路径即可以HTML格式显示图像。

相关问题