How to convert Base64 String to image in PYTHON - python

i am scraping amazon products image but in some time i get base64 string not image link , so i want to convert this string to image .
i tried this code but got error
CODE:
import base64
from PIL import Image
from io import BytesIO
f = open('C:\\Users\\pc\\Desktop\\base64.txt','r')
data = f.read()
im = Image.open(BytesIO(base64.b64decode(data)))
im.save('C:\\Users\\pc\\Desktop\\image.png', 'PNG')
ERROR:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\pc\AppData\Local\Programs\Python\Python39\lib\base64.py", line 87, in b64decode
return binascii.a2b_base64(s)
binascii.Error: Invalid base64-encoded string: number of data characters (16369) cannot be 1 more than a multiple of 4
Base64:
data:image/webp;base64,UklGRrQ6AABXRUJQVlA4IKg6AAAw7ACdASo/ASwBPrFKmkekIiEU2r5ERAsE4vviiQDHoCPrX4ipDeU/JuPLgv9g5f/vXfT/5vrH/s/qE88r+7/9n1P/tb+w/vM/kr75v8p6gH9m6n30FumL/wPnoYPxqT4d+cn5bou5Z+13U778/6/rN/n/Cf5fakHuPwU9xhtf+t9BT2k+7+cn9950fxn+y9gPzQ/8fjAfiv+j7A/9V/x//h/yHu//6Xla+wfYU6ZnpANu0pY3+8S8ONu6NNpvsCTLf6sfvCGmXMtg7P4aXvlaOF3TNN8ZLla6Xpgb7dV+v1cbQa3mGtirv9YSCjpI4FqZ0HrmJJq0vdN8hQkImfY8uy/DuGgZjG5Yw/8RclGmJb1UFLmkmyMtihwG6WQ07KgsmuCLkMg4pU7Da2fVD4DvlQdD0nXJCp3uDJGRO5chKHiN9KNLDtpu2NiSRgr9xXE7JpfDTBoBwPG/+j9pwMWPKo4xTR/Om414TgAqc3s6pFmbE5UkDUt+jE/chNHYIc9woxGtvEGHvHbjKvDkaZeo4OTGNOcPOJQlDzqDctPItImJAWfaQB0fuzHan1+6gQwVu/JBHm3vq3lls+IN+M4kYz8c8NPQZobVVmccv28CRX2e2H84POP3eGm72nOiIyaTujdfiiya7shwA3ra9m/+WasB2+K6neqo+hl0NNy9w2uQvwng8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US5RhYo/StyvaGcvHRbcWdj3tDHgeXshJdRyJ0rwpdvb9uI2zmotJlS0/CgXHa/EOS/ZwopFA+PcoxBlluBNhRIqm/q9iqYNNdpCL8cx+2+QzLwpoq5W8LaWk+KWgxBawIA8vwoO7+r1oFZlftRbPCulu7/9T2vhl44p4tTi8ww7KM50r5h3jD17xSeR+rw9AaxKnxpfVhBrJ5eC+J3+TAC7AzNcrdZgeSMkVMIYp3HgM5Rt54qiMUyLMCqx3FIaTFgj86nugn98OksA7yRpkKw/5hEks52yVQj98p0235MrpmmlThaSrLozPGh37OZNdEGVAJNEUvzuuv1AbTqqM0ZXbQ1sE1a8GelGZu2vhadTVd8d0sDqDNCe9Rnhfb5eDfCQyoEz65lnWGhDJAvSIDewS4kr+WpMpNMm/sjrGOyB2qO0S9p71jBXD9tRjWWfny/YscjjtqSEeag1g5sIPqJsVk+GKoYMp99dWszRE6guyX031zsn2z28ZpVWTXBOYzul7itgP5+we/B1iHXFDmrKezWMo85XL0pgkt6bLNEMVpEH4wvw8CZLQQV+52t8kUzAvlLoZCgOtxYLFqNlXrYdkCzLhRbNyxpen9HAGGf6EIcQ7ekVJdTPsU4K5BITZ9H9Qg+saupxI2JW59vTZZhCFVLSGRmLAxmwwkYAmsiUl5GPDej1+mhrElllxtdOtP9E5pVPywG1zmQKB9nrn4Wwof4CCrJnh91LS8VstgAAJzO22meOSbfg/x4NqUJLqMZLAPa8b56F8Uacc/4wZ83YriLaIm4nasz+shx/m8IvER8DGFT2RDSbG33C2CFS53QbrueMbQ5xUxcC9N29SQftdzxtHF6kgnpeVlTHzLixgdefqHsjjxzhiJoSNo8o3p0cbV8lucaw3Ex8J6XH8LKkcVSgPcLeKw0m9ucADQ+1Mugtxz/UwPlbBEctAAAAAA
i know there are many of questions like this one but i didn't find good answer

This data is not exactly base64 notice the prefix data:
data:image/webp;base64,
This data must be stripped first, then it's valid base64 to be processed as an image.
import base64
from PIL import Image
from io import BytesIO
f = open('C:\\Users\\pc\\Desktop\\base64.txt','r')
data = f.read()
prefix = 'data:image/webp;base64,'
cut = data[len(prefix):]
im = Image.open(BytesIO(base64.b64decode(cut)))
im.save('C:\\Users\\pc\\Desktop\\image.png', 'PNG')

Related

compressing numpy array with zlib + base64 [python]

I'm trying to send a numpy array through the python requests module to a flask server.
First, I compressed the numpy array with zlib, then used base64 to encode the data, then tried to decode and decompress but it's not working.
import numpy as np
import base64
import zlib
import requests
frame = np.random.randint(0,255,(5,5,3)) # dummy rgb image
# compress
data = zlib.compress(frame)
print('compressed')
print(data)
print(len(data))
print(type(data))
data = base64.b64encode(frame)
print('b64 encoded')
print(data)
print(len(data))
print(type(data))
data = base64.b64decode(data)
print('b64 decoded')
print(data)
print(len(data))
print(type(data))
data = zlib.decompress(data)
print('b64 decoded')
I'm getting the following error:
Traceback (most recent call last):
File "client.py", line 26, in <module>
data = zlib.decompress(data)
zlib.error: Error -3 while decompressing data: incorrect header check
data = base64.b64encode(frame) should be
b64encode (data)
You’re accidentally encoding the wrong thing ...
I just realized after considering the extra length for base64 encoded string, I can completely get rid of it.
So, the following code snippet does what I need, it compresses the numpy array, then I can get the original array back without using base64. It gets rid of some of the overhead.
import numpy as np
import base64
import zlib
import requests
frame = np.random.randint(0,255,(5,5,3)) # dummy rgb image
# compress
data = zlib.compress(frame)
print('compressed')
print(data)
print(len(data))
print(type(data))
data = zlib.decompress(data)
print('b64 decoded')
data = np.frombuffer(data, dtype=np.uint8)
print(data)
print(type(data))

How to base64 encode an image using python

I have a stream of data that comes from a device and I need to convert it into a jpeg and then base64 encode it to transfer it over the network.
My Python 2.7 code so far looks like this:
from PIL import Image
import io
image = Image.open(io.BytesIO(self.imagebuffer)) # Image buffer contains the image data from the device.
image.save("test.jpg") # Writes the image to the disk in jpeg format
image.show() # Opens the image using the OS image view
I can see I have the image I want and can save it to the disk in jpeg format.
What I don't understand is if I can base64 encode the image from the image object or if I need to write it to the disk first. I would like to avoid writing it if possible.
The 2nd question I have is what is PIL doing in this process? Is it taking the data and putting the required special codes into the file to make it a jpeg file? I think the answer tot his is yes as I can change the file extension to .bmp and the correct file is written on the disk.
So in summary, is it possible to get a base64 encoded version of my jpeg file from the image object without writing it to disk first?
Try this code
Image base64 encoded format
Python code:
import os
import base64
image = 'test.jpg'
encoded_string = ""
with open(image, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read())
file = encoded_string
This code does the job:
from PIL import Image
import io
import base64
import cStringIO
image = Image.open(io.BytesIO(imagebuffer))
encodingbuffer = cStringIO.StringIO()
image.save(encodingbuffer, format="JPEG")
encodedimage = base64.b64encode(encodingbuffer.getvalue())
Save the img in a buffer - doesn't touch disk
regex for jpeg headers and footers - fault tolerance ( Header: FF D8 FF, Footer: FF D9)
base64 the data
flush to file
I`m working with .dwg file and Python 2.7, this works for me:
import os
import base64
# Open the file
infile = open(input_file, 'r')
# 'r' says we are opening the file to read, infile is the opened file object that we will read from
# encode file to base64
base64EncodedStr = base64.b64encode(infile.read())
Please try this to base64 encode an image using python
import base64
with open("test.jpg", "rb") as image_file:
encoded_string = base64.b64encode(image_file.read())
print(encoded_string)
OR
import base64
image = open('test.jpeg', 'rb')
image_read = image.read()
image_encode = base64.b64encode(image_read)
print(image_encode)

Read image from URL and keep it in memory

I am using Python and requests library. I just want to download an image to a numpy array for example and there are multiple questions where you can find different combinations (using opencv, PIL, requests, urllib...)
None of them work for my case. I basically receive this error when I try to download the image:
cannot identify image file <_io.BytesIO object at 0x7f6a9734da98>
A simple example of my code can be:
import requests
from PIL import Image
response = requests.get(url, stream=True)
response.raw.decode_content = True
image = Image.open(response.raw)
image.show()
The main this that is driving me crazy is that, if I download the image to a file (using urllib), the whole process runs without any problem!
import urllib
urllib.request.urlretrieve(garment.url, os.path.join(download_folder, garment.get_path()))
What can I be doing wrong?
EDIT:
My mistake was finally related with URL formation and not with requests
or PIL library. My previous code example should work perfectly if the URL is correct.
I think you are using data from requests.raw object somehow before save them in Image but requests response raw object is not seekable, you can read from it only once:
>>> response.raw.seekable()
False
First open is ok:
>>> response.raw.tell()
0
>>> image = Image.open(response.raw)
Second open throws error (stream position is on the end of file already):
>>> response.raw.tell()
695 # this file length https://docs.python.org/3/_static/py.png
>>> image = Image.open(response.raw)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3/dist-packages/PIL/Image.py", line 2295, in open
% (filename if filename else fp))
OSError: cannot identify image file <_io.BytesIO object at 0x7f11850074c0>
You should save data from requests response in file-like object (or file of course) if you want to use them several times:
import io
image_data = io.BytesIO(response.raw.read())
Now you can read image stream and rewind it as many times as needed:
>>> image_data.seekable()
True
image = Image.open(image_data)
image1 = Image.open(image_data)

IOError: cannot identify image file when loading images from pdf files

I am trying to read scanned images from a pdf using wand and display it using PIL. But I get some error. First page of the pdf file works perfectly but the second page shows this error.
Code
from wand.image import Image
from wand.display import display
from PIL import Image as PI
import pyocr
import pyocr.builders
import io
import numpy as np
import cStringIO
tool = pyocr.get_available_tools()[0]
lang = tool.get_available_languages()[1]
req_image = []
final_text = []
image_pdf = Image(filename="DEEP_PLAST_20.700.pdf", resolution=200)
image_jpeg = image_pdf.convert('jpeg')
img_page = Image(image=image_jpeg.sequence[1])
img_buffer = np.asarray(bytearray(img_page.make_blob()), dtype=np.uint8)
print(img_buffer)
# im = PI.fromarray(img_buffer)
im = PI.open(cStringIO.StringIO(img_buffer))
I get this error.
Traceback (most recent call last):
File "ocr.py", line 43, in <module>
im = PI.open(cStringIO.StringIO(img_buffer))
File "/home/sahil/anaconda2/lib/python2.7/site-packages/PIL/Image.py", line 2452, in open
% (filename if filename else fp))
IOError: cannot identify image file <cStringIO.StringI object at 0x7fc4a8f168b0>
I don't why the code fails on the second page of the pdf whereas it works for the first one.
Any help would be appreciated!

Python - how to read an image from a URL?

I am completely new to Python and I'm trying to figure out how to read an image from a URL.
Here is my current code:
from PIL import Image
import urllib.request, io
URL = 'http://www.w3schools.com/css/trolltunga.jpg'
with urllib.request.urlopen(URL) as url:
s = url.read()
Image.open(s)
I get the following error:
C:\python>python image.py
Traceback (most recent call last):
File "image.py", line 8, in <module>
Image.open(s)
File "C:\Anaconda3\lib\site-packages\PIL\Image.py", line 2272, in open
fp = builtins.open(filename, "rb")
ValueError: embedded null byte
I have no idea what any of this means. What am I doing wrong?
Image.open() expects filename or file-like object - not file data.
You can write image locally - i.e. as "temp.jpg" - and then open it
from PIL import Image
import urllib.request
URL = 'http://www.w3schools.com/css/trolltunga.jpg'
with urllib.request.urlopen(URL) as url:
with open('temp.jpg', 'wb') as f:
f.write(url.read())
img = Image.open('temp.jpg')
img.show()
Or you can create file-like object in memory using io module
from PIL import Image
import urllib.request
import io
URL = 'http://www.w3schools.com/css/trolltunga.jpg'
with urllib.request.urlopen(URL) as url:
f = io.BytesIO(url.read())
img = Image.open(f)
img.show()
EDIT: 2022
Because urlopen() also gives file-like object so you can even skip io and use directly url (without .read()) in Image.open()
from PIL import Image
import urllib.request
URL = 'http://www.w3schools.com/css/trolltunga.jpg'
with urllib.request.urlopen(URL) as url:
img = Image.open(url)
img.show()
Here's how to read an image from a URL using scikit-image
from skimage import io
io.imshow(io.imread("http://www.w3schools.com/css/trolltunga.jpg"))
io.show()
Note: io.imread() returns a numpy array
To begin with, you may download the image to your current working directory first
from urllib.request import urlretrieve
url = 'http://www.w3schools.com/css/trolltunga.jpg'
urlretrieve(url, 'pic.jpg')
And then open/read it locally:
from PIL import Image
img = Image.open('pic.jpg')
# For example, check image size and format
print(img.size)
print(img.format)
img.show()
As suggested in this stack overflow answer, you can do something like this:
import urllib, cStringIO
from PIL import Image
file = cStringIO.StringIO(urllib.urlopen(URL).read())
img = Image.open(file)
Then you can use your image freely.
For example, you can convert it to a numpy array:
img_npy = np.array(img)

Categories