简体   繁体   中英

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...

I have some data, and I get RGB img with the line below:

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) ?

Thank you for your help

With Node JS, I can get the correct base64 with these lines :

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...

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):

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:

import base64

base64.b64encode(img.tobytes())

See tobytes() method of Image object.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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