Reputation: 222
I am trying to do the exact same thing in python as what I can in JavaScript. In JavaScript I can easily draw on a canvas and then use toDataUrl(imageFormat, quality) to get the image in base64 encoded string.
Is there anything in Python that can do the exact same thing?
I have done this in Python
from PIL import Image,
im = Image.new('L', (width, height))
output = StringIO()
im.save(output, "JPEG", quality=89)
but the output is not in JPEG format. I believe that it is in PNG.
So is there anyway that I can perform the same thing as what the todataurl url does? I need this to be in jpeg and at a specific quality.
If anyone has any ideas on how to go about this, it will be much appreciated
Upvotes: 0
Views: 1558
Reputation: 620
Try this:
import base64
from PIL import Image
import StringIO
im = Image.new('L', (width, height))
output = StringIO.StringIO()
im.save(output, "JPEG", quality=89)
encoded_string = base64.b64encode(output.getvalue())
sample output with width=50 and height=50:
/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAQCAwMDAgQDAwMEBAQEBQkGBQUFBQsICAYJDQsNDQ0LDAwO
EBQRDg8TDwwMEhgSExUWFxcXDhEZGxkWGhQWFxb/wAALCAAyADIBAREA/8QAHwAAAQUBAQEBAQEAAAAA
AAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEI
I0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1
dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi
4+Tl5ufo6erx8vP09fb3+Pn6/9oACAEBAAA/APz/AKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK
KKKKKKKKKK//2Q==
Upvotes: 1