I can read a jpg image from disk via PIL, Python OpenCV, etc. into a numpy array via some built-in functions such as (in the case of OpenCV) arr= cv2.imread(filename).
But how do I decode a jpg in binary format directly from memory?
Use case: I want to put a jpg image into a database in binary format and then read it from the db into memory and decode it to a numpy array.
Is this possible?
Assuming that you are storing the image data in your db as a string, you first need to construct a numpy array from that string that can later be converted to an image using cv2.imdecode. For example:
img = cv2.imdecode(np.fromstring(img_data, dtype=np.uint8), cv2.IMREAD_UNCHANGED)
for Python3 use this way:
from scipy import misc
import io
f = open('file.png', 'rb')
fs = f.read()
likefile = io.BytesIO(fs)
face1 = misc.imread(likefile)
Python2 has StringIO.
Fetching Images from Url to Jpg
import requests
from io import BytesIO
response = requests.get("https://optse.ztat.net/teaser/ES/CW15_ES_bermuda_men.jpg")
my_img_In_byts = BytesIO(response.content).read()
path="C:/Users/XX/Desktop/TryingPython/downloadedPic.jpg"
my_fprinter = open(path, mode='wb')
print( my_fprinter .write(my_img_In_byts))
my_fprinter.close()
print("Done")
Related
I'm trying to send json dict that should contain Pillow image as one of his fields, to do that I have to convert the image to string.
I tried to use pillow function:
image.toString()
but still got it as bytes, so I tried to encode it:
buff = BytesIO()
image.save(buff, format="JPEG")
img_str = base64.b64encode(buff.getvalue())
but still got it as bytes.
How can I convert Pillow images to format that can be saved in json file?
In the comments, Mark Setchell suggests calling .decode('ascii') on the result of your b64encode call. I agree that this will work, but I think base64encoding to begin with is introducing an unnecessary extra step that complicates your code.*
Instead, I suggest directly decoding the bytes returned by image.tostring. The only complication is that the bytes object can contain values larger than 128, so you can't decode it with ascii. Try using an encoding that can handle values up to 256, such as latin1.
from PIL import Image
import json
#create sample file. You don't have to do this in your real code.
img = Image.new("RGB", (10,10), "red")
#decode.
s = img.tobytes().decode("latin1")
#serialize.
with open("outputfile.json", "w") as file:
json.dump(s, file)
(*but, to my surprise, the resulting json file is still smaller than one made with a latin1 encoding, at least for my sample file. Use your own judgement to determine whether file size or program clarity is more important.)
I use the following to exchange Pillow images via json.
import json
from PIL import Image
import numpy as np
filename = "filename.jpeg"
image = Image.open(filename)
json_data = json.dumps(np.array(image).tolist())
new_image = Image.fromarray(np.array(json.loads(json_data), dtype='uint8'))
1) I have an image that I converted to a string. It looks like this:
bytesimage = b'iVBORw0KGgoAAAANSUhEUgA.... etc etc
2) I can convert it to an 'bytesimage.png' using:
def StringToImage(self, stringname, imageoutput):
imgdata = base64.b64decode(stringname)
imagename = imageoutput
with open(imagename, 'wb') as f:
f.write(imgdata)
3) But then I want to save that image or string to memory to use in wxpython interface without needing to save the file. I have seen several related questions where the solution is using io.BytesIO, but I just cant connect the steps and both wxpython or PIL don't seem to read the bytes properly.
So to clarify:
I have a image stored in a string DONE
I can convert that to an image (if needed) but dont want to save it DONE
I need that string OR image (whichever is best) saved to memory NEEDS SOLVING
Then I want to be able to use that image in wxpython (I can open in PIL first if required)
Any help would be fantastic!
StringIO seems to be the way to go. It allows you to pass the decoded string directly to PIL.
import base64
from PIL import Image
import StringIO
# Banana emoji (JPG) as a b64 string.
b64_img_str = '/9j/4AAQSkZJRgABAQEAYABgAAD/4QCKRXhpZgAATU0AKgAAAAgABVEAAAQAAAAIAAAASlEBAAMAAAABA+YAAFECAAEAAAAYAAAAalEDAAEAAAABAAAAAFEEAAEAAAABBgAAAAAAAAAAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAP//AP///8zMAP8AADBkAP8A/5iYAP/bAEMAAgEBAgEBAgICAgICAgIDBQMDAwMDBgQEAwUHBgcHBwYHBwgJCwkICAoIBwcKDQoKCwwMDAwHCQ4PDQwOCwwMDP/bAEMBAgICAwMDBgMDBgwIBwgMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDP/AABEIACMAIQMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRo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Dxd+x58Qvih8Y7nVvhP4J/4QfU47jSfEeoX76l4svX0vVLG0snfWb281hYbe6v5SkNxcRWpmlge2s5JLqS5H9E/w4/aF8A/GPxV4n0Lwj448H+Ktb8E3f2DxFp+j6zbX11oFxvlTybuKJ2e3k3wzLskCnMUgxlTj8YP2qv8AgoZrGs/tafCjXvid8OfGHw7+E/hHxZ/amk6b47N34JufHmsWqXZ0wwyXLQwQaba38enXdxLfOshL2rfZTHDIK/Qn/gmH/wAEyvE37Efgv4b2XjLxx4Z8US/CvwhqXhLw3a+HvCqaHHaW+qXtlfX32yRZWW/mEun2ix3KW9o7gXEs6TTTl4/yfwZo5zLA18fxBSVHE1pJumk24RirQVSbblOq7tycm5JWVopKK9jPMyw+KxPLhoxjGKStFPlXpdtu+7u279dj7Gooor9nPHCv5YdU/bu+Jmvf8Fufhd+zjqGqeH9R+EXwT/aA03wT4E0u78K6TcX/AIW0fT/E1pbWtta6m9sdQTENjaxySfaPMnWICV5MtkooA6D/AILcf8FQPjV/wTu/4Lr/ALQUnwd8ReH/AAfqGqf2It1qn/CHaLqGqyxSeH9GL2/226tJbkW5a3hfyBIIg6bwm4lj/S98J/hboPwO+FnhnwT4Wsf7L8M+D9KtdE0iz86Sf7JZ20KQwReZIzSPtjRV3OzMcZJJyaKKAOgooooA/9k='
# Decode back to the original bytes
new_img_str = base64.b64decode(b64_img_str)
# Use StringIO to provide an in-memory buffer that we can use
# to pass the image string to PIL.
sio = StringIO.StringIO(new_img_str)
img = Image.open(sio)
# Display the image
img.show()
In C#, I can use Bitmap.lockbits() to access a bitmap as a byte array. How to do this in PIL? I have tried Image.write() but it wrote a full format image to a stream.
from io import BytesIO
from PIL import Image
with BytesIO() as output:
with Image.open(path_to_image) as img:
img.save(output, 'BMP')
data = output.getvalue()
.. warning::
This method returns the raw image data from the internal
storage. For compressed image data (e.g. PNG, JPEG) use
:meth:~.save, with a BytesIO parameter for in-memory
data.
This is the warning in the tobytes method. So we can use the save method with a BytesIO parameter to get a compressed byte array.
import io
byteIO = io.BytesIO()
image.save(byteIO, format='PNG')
byteArr = byteIO.getvalue()
I'd like to work directly with compressed JPEG images. I know that with PIL/Pillow I can compress an image when I save it, and then read back the compressed image - e.g.
from PIL import Image
im1 = Image.open(IMAGE_FILE)
IMAGE_10 = os.path.join('./images/dog10.jpeg')
im1.save(IMAGE_10,"JPEG", quality=10)
im10 = Image.open(IMAGE_10)
but, I'd like a way to do this without the extraneous write and read. Is there some Python package with a function that will take an image and quality number as inputs and return a jpeg version of that image with the given quality?
For in-memory file-like stuff, you can use StringIO.
Take a look:
from io import StringIO # "import StringIO" directly in python2
from PIL import Image
im1 = Image.open(IMAGE_FILE)
# here, we create an empty string buffer
buffer = StringIO.StringIO()
im1.save(buffer, "JPEG", quality=10)
# ... do something else ...
# write the buffer to a file to make sure it worked
with open("./photo-quality10.jpg", "w") as handle:
handle.write(buffer.contents())
If you check the photo-quality10.jpg file, it should be the same image, but with 10% quality as the JPEG compression setting.
Using BytesIO
try:
from cStringIO import StringIO as BytesIO
except ImportError:
from io import BytesIO
def generate(self, image, format='jpeg'):
im = self.generate_image(image)
out = BytesIO()
im.save(out, format=format,quality=75)
out.seek(0)
return out
StringIO is missing in Python3.0, ref to : StringIO in python3
I want to convert some base64 encoded png images to jpg using python. I know how to decode from base64 back to raw:
import base64
pngraw = base64.decodestring(png_b64text)
but how can I convert this now to jpg? Just writing pngraw to a file obviously only gives me a png file. I know I can use PIL, but HOW exactly would I do it? Thanks!
You can use PIL:
data = b'''iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAAAXNSR0IArs4c6QAAAIBJRE
FUOMvN08ENgCAMheG/TGniEo7iEiZuqTeiUkoLHORK++Ul8ODPZ92XS2ZiADITmwI+sWHwi
w2BGtYN1jCAZF1GMYDkGfJix3ZK8g57sJywteTFClBbjmAq+ESiGIBEX9nCqgl7sfyxIykt
7NUUD9rCiupZqAdTu6yhXgzgBtNFSXQ1+FPTAAAAAElFTkSuQmCC'''
import base64
from PIL import Image
from io import BytesIO
im = Image.open(BytesIO(base64.b64decode(data)))
im.save('accept.jpg', 'JPEG')
In very old Python versions (2.5 and older), replace b''' with ''' and from io import BytesIO with from StringIO import StringIO.
Right from the PIL tutorial:
To save a file, use the save method of the Image class. When saving files, the name becomes important. Unless you specify the format, the library uses the filename extension to discover which file storage format to use.
Convert files to JPEG
import os, sys
import Image
for infile in sys.argv[1:]:
f, e = os.path.splitext(infile)
outfile = f + ".jpg"
if infile != outfile:
try:
Image.open(infile).save(outfile)
except IOError:
print "cannot convert", infile
So all you have to do is set the file extension to .jpeg or .jpg and it will convert the image automatically.