Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 923
florian Avatar asked Jan 12 '18 15:01

florian


People also ask

Can we convert image to Base64?

Convert Images to Base64 Just select your JPG, PNG, GIF, Webp, or BMP picture or drag & drop it in the form below, press the Convert to Base64 button, and you'll get a base-64 string of the image. Press a button – get base64. No ads, nonsense, or garbage. Drag and drop your image here!

How do I convert a file to Base64?

Convert Files to Base64 Just select your file or drag & drop it below, press the Convert to Base64 button, and you'll get a base64 string. Press a button – get base64. No ads, nonsense, or garbage. The input file can also be an mp3 or mp4.

Does Base64 encoding reduce image quality?

With the introduction of multiplexing that arrived with HTTP/2, web browsers have become incredibly efficient in delivering hundreds of files through a single connection. This works around most limits that the Base64 encoding solved and in fact means Base64 now does more bad than good.


1 Answers

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)
like image 166
florian Avatar answered Sep 28 '22 05:09

florian