Get binary image data in Python - python

How do I take an image and turn that into binary image data?
This is what I have tried:
class get_binary_data(image_url):
#Get the image online online_image = http://www.myimg.com/test.jpg
online_image = requests.get(image_url).content
image_data = BytesIO(online_image)
However this does not seem to give me the binary image data, could someone help explain the process of getting the binary image data?
This is what I'm trying to do:
app = subprocess.Popen("externalApp",
in=subprocess.PIPE,
out=subprocess.PIPE)
app.in.write(image_data)
app.in.close()
which gives me the error:
IOError: [Errno 32] Broken pipe

You do not need to wrap the response data in a BytesIO object just to write it to a pipe. Use the response.content data directly:
class get_binary_data(image_url):
#Get the image online online_image = http://www.myimg.com/test.jpg
return requests.get(image_url).content
I used a BytesIO object in my answer to your previous question only because you wanted to load that data into a PIL Image object. It is a requirement for Image.open() that a file-like object with seek support is provided, and BytesIO does just that.
Here, however, you need a (byte)string, so just use the .contents value.

Related

Uploading Image with PIL+twython on twitter without saving it

After much searching I finally found it. Here's the response.
Step 1
code for the user to provide the link and for PIL to resize it according to some conditions (not relevant to the question).
PIL opens the image file link like this:
img=Image.open(io.BytesIO(requests.get(url).content))
where url is the link.
Step2
then PIL must save it AND seek(0) on the io.BytesIO class:
blob = io.BytesIO()
img.save(blob, 'JPEG')
blob.seek(0)
response = twitter.upload_media(media=blob);
Step 3
Proceed according to the documendation:
twitter.update_status(status='Checkout this cool image!', media_ids=[response['media_id']])
Twython's documendation is outdated and StringIO() has changed package and also doesn't take bytes objects. I also can't get the logic behind making a bytes object to a string and then send it as a bytes object.
https://twython.readthedocs.io/en/latest/usage/advanced_usage.html
The media parameter also takes io.BytesIO class objects as shown above and in this simpler example below:
response = twitter.upload_media(media=io.BytesIO(requests.get(url).content));

How to convert to bytes format for PIL images which is similar to normal bytes format

Sorry that I couldnt explain clearly in subject.
I used read() to read the entire image in the form of bytes and also I used PIL's tobytes() to read the same image. But to me the image bytes looks different. Could you please advice on how to have the same bytes generated using read() using PIL's package utility? From raw encoding to utf-8
Code sample:
path3 = r'path'
with io.open(path3, 'rb') as image_file:
content1 = image_file.read()
b'\xff\xd8\x ...
Using PIL:
with io.open(path3, 'rb') as image_file:
content1 = Image.open(image_file).tobytes()
b'\xbf\x91\xc0\xbf\x91\xc0\xbe\x90\xbf\xbe'
In my use case:
from pdf2image import convert_from_bytes
images = convert_from_bytes(open('pp.pdf', 'rb').read())
b=images[0].read() # since this returns list format
AttributeError: 'PpmImageFile' object has no attribute 'read'
Is it possible to have same byte format like read()?
PIL is doing more than just reading the bytes of the image file. It is decompressing it from JPG or PNG or whatever format you are giving it. It's tobytes function returns all the pixel values.
In the first snippet you are simply reading in the bytes of the compressed image file. These will always be different unless you are using an uncompressed file format like BMP.

Store a base64 image in python memory, then retrieve for use in wxpython/PIL

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/bAEMAAgEBAgEBAgICAgICAgIDBQMDAwMDBgQEAwUHB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t0Yig6TWt01dNf10egUUUV9Yc4V8n/8ABQDUfgL+3D+xf8ffB2q/EzwfJH8OfD+rnxJq2h6h/a2p/DW4FjfQSXU1vYyi6jkSJb2OS2yhuYRdWzh45ZY2+sK/A/8Aag8G6PYftY6D8LPD7ah+0b4N+DOn+D/hN4hi8B/Cj/hI5vC/hew1h9Vl0/Xmt5pJb6/a40HRoHkGy0jjl1gR6etwWiPBmmPWDws8Q4ubim1GKblJpN8sUk227WStq9AVuZRbtd2PGPHvh39pDxd+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()

PIL.Image.open() gives IOError: cannot identify image file

I'm trying to save a jpg image from a Flask app form. The following code works fine:
blob = request.files[canvas_key]
blob.stream.seek(0)
data = blob.stream.read()
string_io = cStringIO.StringIO(data)
string_io has type <cStringIO.StringI object at 0x10bf2bf10>.
Yet when I try: Image.open(string_io), I get this error: IOError: cannot identify image file.
Using stream.seek(0) seems to solve this problem for other people, but in my case it hasn't.
Thanks to #Mark, I changed the image type I capture from WebP to PNG.

Python/Django download Image from URL, modify, and save to ImageField

I've been looking for a way to download an image from a URL, preform some image manipulations (resize) actions on it, and then save it to a django ImageField. Using the two great posts (linked below), I have been able to download and save an image to an ImageField. However, I've been having some trouble manipulating the file once I have it.
Specifically, the model field save() method requires a File() object as the second parameter. So my data has to eventually be a File() object. The blog posts linked below show how to use urllib2 to save your an image URL into a File() object. This is great, however, I also want to manipulate the image using PIL as an Image() object. (or ImageFile object).
My preferred approach would be then to load the image URL directly into an Image() object, preform the resize, and convert it to a File() object and then save it in the model. However, my attempts to convert an Image() to a File() have failed. If at all possible, I want to limit the number of times I write to the disk, so I'd like to do this object transformation in Memory or using a NamedTemporaryFile(delete=True) object so I don't have to worry about extra files laying around. (Of course, I want the file to be written to disk once it is saved via the model).
import urllib2
from PIL import Image, ImageFile
from django.core.files import File
from django.core.files.temp import NamedTemporaryFile
inStream = urllib2.urlopen('http://www.google.com/intl/en_ALL/images/srpr/logo1w.png')
parser = ImageFile.Parser()
while True:
s = inStream.read(1024)
if not s:
break
parser.feed(s)
inImage = parser.close()
# convert to RGB to avoid error with png and tiffs
if inImage.mode != "RGB":
inImage = inImage.convert("RGB")
# resize could occur here
# START OF CODE THAT DOES NOT SEEM TO WORK
# I need to somehow convert an image .....
img_temp = NamedTemporaryFile(delete=True)
img_temp.write(inImage.tostring())
img_temp.flush()
file_object = File(img_temp)
# .... into a file that the Django object will accept.
# END OF CODE THAT DOES NOT SEEM TO WORK
my_model_instance.image.save(
'some_filename',
file_object, # this must be a File() object
save=True,
)
With this approach, the file appears corrupt whenever I view it as an image. Does anyone have any approach that takes a file file from a URL, allows one to manipulate it as an Image and then save it to a Django ImageField?
Any help is much appreciated.
Programmatically saving image to Django ImageField
Django: add image in an ImageField from image url
Update 08/11/2010: I did end up going with StringIO, however, I was stringIO was throwing an unusual Exception when I tried to save it in a Django ImageField. Specifically, the stack trace showed a name error:
"AttribueError exception "StringIO instance has no attribute 'name'"
After digging through the Django source, it looks like this error was caused when the model save tries to access the size attribute of the StringIO "File". (Though the error above indicates a problem with the name, the root cause of this error appears to be the lack of a size property on the StringIO image). As soon as I assigned a value to the size attribute of the image file, it worked fine.
In an attempt to kill 2 birds with 1 stone. Why not use a (c)StringIO object instead of a NamedTemporaryFile? You won't have to store it on disk anymore and I know for a fact that something like this works (I use similar code myself).
from cStringIO import StringIO
img_temp = StringIO()
inImage.save(img_temp, 'PNG')
img_temp.seek(0)
file_object = File(img_temp, filename)

Categories