简体   繁体   English

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

[英]How to convert Image PIL into Base64 without saving

I generate an image with Python, and I need to convert this Pil Image into a Base64, without saving this one into any folder...我用Python生成了一个图像,我需要将此Pil Image转换为Base64,而不将此图像保存到任何文件夹中...

I have some data, and I get RGB img with the line below:我有一些数据,我得到了带有以下行的 RGB img:

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

What is the simple way to convert this PIL into base64 ?(I can't open a file image because I must not save the img) ?将此 PIL 转换为 base64 的简单方法是什么?(我无法打开文件图像,因为我不能保存 img)?

Thank you for your help感谢您的帮助

With Node JS, I can get the correct base64 with these lines :使用 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); }); 
}) 

But I have to save the file if I use NodeJS...但是如果我使用NodeJS,我必须保存文件......

this is the code to generate the matrix from the image, you don't need to know what is in data ;)这是从图像生成矩阵的代码,您不需要知道数据中的内容;)

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)

I found the solution.我找到了解决方案。 Hope this helps !希望这可以帮助 !

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)

@florian answer helped me a lot but base64.b64encode(img_byte) returned bytes so I needed to decode it to string before concatenation (using python 3.6): @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()

You can use base64 library like this:您可以像这样使用base64库:

import base64

base64.b64encode(img.tobytes())

See tobytes() method of Image object.参见Image对象的tobytes()方法。

Or you can use something like this:或者你可以使用这样的东西:

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)}">'

Just pass path of image in get_thumbnail function and image_formatter to display it in HTML.只需在get_thumbnail函数和image_formatter传递图像路径即可在 HTML 中显示它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM