I am creating a wordcloud image with this code.
wordcloud = WordCloud(
background_color='white',
random_state=30,
width=1500,
height=1200,
font_path = font_path,
prefer_horizontal=1)
wordcloud.generate_from_frequencies(frequencies=d)
I show the image with matplotlib like this:
plt.imshow(wordcloud)
plt.axis('off')
plt.show()
I am using this as part of a web app. I want to convert this image to base64 and store as a string as a value in a dictionary key for a specific instance. I see a lot of posts about how to convert images to base64 but it looks like they involve saving the figure locally before encoding. How do I do this without saving anywhere so I can just go from image to string?
This code looks kind of like what I want.
import base64
from PIL import Image
from io import BytesIO
with open("image.jpg", "rb") as image_file:
data = base64.b64encode(image_file.read())
im = Image.open(BytesIO(base64.b64decode(data)))
im.save('image1.png', 'PNG')
If I just did this, would this accomplish my task?
data = base64.b64encode(wordcloud)
If I just did this, would this accomplish my task?
data = base64.b64encode(wordcloud)
No. You need to "save" the image, get that bytestream, and encode that to base64. You don't have to save the image to an actual file; you can actually use a buffer.
w = WordCloud().generate('Test')
buffer = io.BytesIO()
w.to_image().save(buffer, 'png')
b64 = base64.b64encode(buffer.getvalue())
And to convert that back and display the image
img = Image.open(io.BytesIO(base64.b64decode(b64)))
plt.imshow(img)
plt.show()
Related
I have the following code to generate GIFs from images, the code works fine and the gif is saved locally, what I want to do rather the saving the GIF locally, I want for example data URI that I could return to my project using a request. How can I generate the GIF and return it without saving it?
my code to generate the GIF
import os
import imageio as iio
import imageio
png_dir='./'
images=[]
for file_name in url:
images.append(file_name)
imageio.imwrite('movie.gif', images, format='gif')
I found I can save it as bytes with the following code
gif_encoded = iio.mimsave("<bytes>", images, format='gif')
it will save the GIF as bytes then you can encode it.
encoded_string = base64.b64encode(gif_encoded)
encoded_string = b'data:image/gif;base64,'+encoded_string
decoded_string = encoded_string.decode()
for more examples check this out
https://imageio.readthedocs.io/en/stable/examples.html#read-from-fancy-sources
How i can save or download this picture with python
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQY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DceJfiZa3s0N3qs0K+Utzbs+kaaPNt2IxLksF2ncoypYZOM5rF1n4m+N7G6RIPEnmI6b42k0ayBkXdgFNgdWHY4bhgV6g19GDS/A13a3623w2tLOeKymuUlu9EgWIFFyASM88jj6+leUm4hFgt4fBXhb7Mf+Wp0OLZ1I+9jHUH8jTkr7HqZXl1fHXnCzS01bWr9DD0Hxd451jT2kt/EcxuooZ7i4jTw/aOkEcaqdzsBkAs+37vBVieBms3xt4/8e+GfFuqaHH4ijvjZ7CJRotvEWVoxISyNFlSAcEHpg+ldlBNZ3MYe28KeEJQCQ+3QkPlqP4mwnTHpnp9Mlxc6dBEkg8M+EMNuI3aCi8Acc7epII/DrQlod74cxrm7Nel3p+ByFh4q+MOo2IvrGSSWyeZIoZv7FgKSht3zK4h2kLtIbng8Hvj2n4U694mOjahF4i1C3nv4rzDLHapEYFaGKQRuBGnzjfzxweM8YHHLNaR3Eco8PeEY5SnnxynQQC5DHBU7Mnpu3cd+4r0f4WahFeaHezDTNHgZr1932WzWNZDtTLkY5J9Tz0ppI5cVkmLoUnUm1a/d/qj2B40kKl1BKnIPoacAAAB0HFFFVY8C5Fd28V3azW1wu+GZDG65IypGCMj2Ncd/wqvwb/0Bv/Jqb/4uiig6KOLr4dNUZuN+za/Id/wq/wAIbAn9ktsBJC/a58Ang/x98D8qb/wqvwb/ANAb/wAmpv8A4uiig2/tTG/8/pf+BP8AzFHwt8HgEDSCAeo+1Tc/+P1s6N4T0XRrZ7fTbLyYXcyMvmu2WIAzlmJ7Ciigipj8VVXLUqya85N/qf/Z
Well, the start of the string (this part data:image/jpeg;base64,) tells you it is base64 encoded. So, you need to strip all that off and find the start the image, which is /9j, and just grab the image part which is the rest of the string.
b = b'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD...'
z = b[b.find(b'/9'):]
Then you need base64 decode the result, and make it into a BytesIO object that PIL can read. Then read it into a PIL Image and save it:
im = Image.open(io.BytesIO(base64.b64decode(z))).save('result.jpg')
So, the entire code will look like:
import base64
import io
from PIL import Image
# Initialise your data
b = b'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD...'
z = b[b.find(b'/9'):]
im = Image.open(io.BytesIO(base64.b64decode(z))).save('result.jpg')
Keywords: image, image processing, base64, b64, encode, encoded, decode, decoded, PIL, Pillow, Python
This is a code of a JPG/PNG(I don't know exactly)
Here's on google docs
I need to decode it in Python to complete image and show it using Pillow or something like that. Do you know any libraries or ways how to decode it? Thanks!
(for Python 3)
If the image is stored as a binary file, open it directly:
import PIL
# Create Image object
picture = PIL.Image.open('picture_code.dat')
#display image
picture.show()
# print whether JPEG, PNG, etc.
print(picture.format)
If the image is stored as hex in a plaintext file picture_code.dat similar to your Google Docs link, it needs to first be converted to binary data:
import binascii
import PIL
import io
# Open plaintext file with hex
picture_hex = open('picture_code.dat').read()
# Convert hex to binary data
picture_bytes = binascii.unhexlify(picture_hex)
# Convert bytes to stream (file-like object in memory)
picture_stream = io.BytesIO(picture_bytes)
# Create Image object
picture = PIL.Image.open(picture_stream)
#display image
picture.show()
# print whether JPEG, PNG, etc.
print(picture.format)
Is there a way to convert a pyplot figure created with pyplot.Figure into a wand image? I have tried using the following to no avail:
image_data = BytesIO()
figure.savefig(image_data, format='png')
image_data.seek(0)
image = Image(file=image_data, resolution=250)
The end goal of this is to convert a list of figures into a long png. The only other method (which is ugly) is to convert to pdf and then concatenate the pages.
I was trying to figure out how to do this same thing. I went down a rabbit hole for a bit thinking I needed to also use PIL (Pillow) to accomplish this task. With the help of the previous answer I was able to come up with a complete example:
import matplotlib
from io import BytesIO
import numpy
import matplotlib.pyplot as plt
from wand.display import display
from wand.image import Image
plt.plot([1,5,3,2])
plt.ylabel('y axis numbers')
plt.xlabel('x axis numbers')
image_data = BytesIO() #Create empty in-memory file
plt.savefig(image_data, format='png') #Save pyplot figure to in-memory file
image_data.seek(0) #Move stream position back to beginning of file
img = Image(file=image_data) #Create wand.image
display(img) #Use wand to display the img
I believe you are on the right track. Without seeing the figure, I would assume the issue would be related to wand holding the C structure pointer using the with keyword.
image_data = BytesIO()
figure.savefig(image_data, dpi=250, format='png')
image_data.seek(0)
with Image(file=image_data) as img:
# ... do work
img.save(filename='/tmp/out.png')
I tried the recommended code above and had no luck. I posted the question to the WandB forum (here) and the following was recommended:
fig, ax1 = plt.subplots(...)
...
buf = io.BytesIO()
plt.savefig(buf, format='png')
buf.seek(0)
wandb.log(({"chart": wandb.Image(Image.open(buf)) }))
fig.show()
It seems that using the file parameter is no longer allowed.
I have a feature with my application where a user can upload a photo. I would like to convert the photo into a JPG file and then upload it to my servers.
The photo is received in base64. I've seen other answers which suggest using PIL however, it saves the image to a local directory. Instead I would like to convert the received image into a base64 JPG image.
How would I do this? Thanks.
try this:
import base64
from PIL import Image
from io import BytesIO
im = Image.open(BytesIO(base64.b64decode(data)))
output = BytesIO()
im.save(output, 'JPEG')
jpg_img = output.read()
it will save the data to a stream ( the same way tou enter it) and then you can read from that stream