Python crashing while opening a image - python

I am getting an image using an API call and eventually need to put the image into a PDF document using ReportLab. Python was crashing without any error messages when I tried canvas.drawImage method in ReportLab. In order to isolate the issue, I just tried opening the image using the Image class and Python still crashes. I can open the image manually using paint and the code does not error out when using other images, leading me to believe I am missing something while converting the binary to the image. I cannot share the images or the API. The definition of the result from the API is as follows.
<GetImageResponse xmlns="http://tempuri.org/">
<GetImageResult>base64Binary</GetImageResult>
<errorMessages>string</errorMessages>
</GetImageResponse>
'''
from zeep import Client
import base64
from PIL import Image, ImageTk
client=Client(wsdl='******.asmx?wsdl')
imgService=client.service.GetImage("***",****, "***********")
imgFile="imageTest.png"
base64_bytes = base64.b64encode(imgService.GetImageResult)
with open(imgFile, "wb") as fh:
fh.write(base64.decodebytes(base64_bytes))
image = Image.open(imgFile)
image.show()
'''
Can someone point me where I need to look? Thanks in advance for any pointers.

Related

How to read an image from a URL in Colab?

I have seen so many different threads about this topic but none of their solutions seems to work for me. I've tried several ways of reading an image from my Drive into Colab using its URL, with no success. I want to read it using its URL rather than mounting my Drive and using directories because multiple people share this Colab, and their directory to the image might not be the same as mine.
The first attempt comes from a popular thread on this issue: How do I read image data from a URL in Python?
from PIL import Image
import requests
url = 'https://drive.google.com/file/d/1z33YPsoMe0lSNNa2XWa0tiK2571j2tFu/view?usp=sharing'
im = Image.open(requests.get(url).raw) # apparently no need for bytes wrapping in new Python versions
im = Image.open(requests.get(url, stream=True).raw) # also does not work
The error I got was UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7f0189569770>
Then I tried:
from skimage import io
io.imshow(io.imread(url))
Which returned ValueError: Could not find a format to read the specified file in mode 'i'. Feeling very lost because all these approaches seem to work for everyone else. Would appreciate any feedback.
Using gdown to read an image from Google Drive into Colab.
If you have your image in your Google Drive and you are using colab.research.google.com, then you can follow these steps:
pip install gdown
Obtaining the share link from your image (remember to set the option "Share to anyone with the link"). For an example:
# https://drive.google.com/file/d/1WG3DGKAo8JEG4htBSBhIIVqhn6D2YPZ/view?usp=sharing
Extract the id of the share link from the URL 1WG3DGKAo8JEG4htBSBhIIVqhn6D2YPZ.
Download the image in the folder content of a particular user who has access to this Colab:
!gdown --id '1WG3DGKAo8JEG4htBSBhIIVqhn6D2YPZ' --output bird1.jpp
Read the image file from the folder content
from PIL import Image
im = Image.open("../content/bird1.jpg")
im

how to fix problem of boxes generated by pdf2image while converting pdf to images.?

I'm trying to convert pdf to images using pdf2image but getting problem of extra generated boxes.
This is my input pdf file screenshot
this in input file
from pdf2image import convert_from_path
images = convert_from_path('input_pdf.pdf',output_folder=r'C:\Users\Baith')
images[0].save('output.jpg')
after executing above code got this output
output_file
Since pdf2image is only a thin wrapper around pdftoppm, itself part of poppler, I would advise trying different parameters with the CLI tools to see it a specific combination works.
As for pdf2image itself, you might want to try use_cropbox=True and see if it still add lines.
Feel free to open an issue directly of the repository, if you can provide a sample PDF I would be happy to assist with the issue.

Qt - Loading image with wrong extension

I'm currently working on a Qt program that works with images that are supplied by the users. One problem I've run into is that a lot of images are saved with the wrong extension - e.g. an image is saved in JPG format but has a PNG extension.
Qt doesn't seem to deal well with this. When I load an image like this into a QImage, the QImage fails to load. I've been looking through the docs, but I haven't come across anything relating to this.
Other programs I've used are able to correctly identify the image as a JPG despite the PNG extension, so there should be no reason for Qt to be unable to do this, but I'm not having any luck.
Any suggestions?
I solved this by using a QImageReader. An example is shown below using PySide.
First I created an instance of QImageReader and set it to read the format from the content.
image_reader = QtGui.QImageReader()
image_reader.setDecideFromContent(True)
This setting tells the reader to only look at the image's data to determine its format and not the extension.
Then I set the filename to the filename of the image I wanted to load and called read().
image_reader.setFileName(file_path_here)
image = image_reader.read()
Read returns a QImage object, so I proceeded with the rest of my code from there.

Display an image read from a zip archive python

I want to create a comic archive reader in python as an exercise to teach myself more python but I've been having troubles trying to read different image files from a zip archive without extracting the files and then display them.
I found a website with an example (http://www.python-forum.org/pythonforum/viewtopic.php?f=4&t=3607) that could only display .gif images. The example uses PhotoImage (The Tkinter version not the PIL version) which can accept a 64bit encoded string instead of an actual file. From most of my research it looks like PIL is what I want to use to deal with images other than gif but I can't find a way to call PIL.ImageTk.PhotoImage in a similar way to the Tkinter.PhotoImage. to take a stream of data instead of an actual file.
Is there any way that I can hand the data received from zipfile.read() to PIL.ImageTk.PhotoImage? Is there another library I could use to handle the images? Tkinter is not a requirement for the program I'm writing so if there is a better widget framework that I should be using I don't mind changing.
EDIT:
So I figured a way to do this with PIL and tkinter.
z = zipfile.ZipFile("zipfile.zip", "r")
data = z.read(z.namelist()[0]) #Read in the first image data
dataEnc = StringIO(data) #Encode the raw data to be used by Image.open()
img = Image.open(dataEnc) #Open the image
pimg = ImageTk.PhotoImage(img) #Make tk compatible image
You can use PythonMagick to create an Image like so:
from PythonMagick import *
data = zipfile.read()
img = Image(Blob(data))
Then display it using wxPython as suggested in the PythonMagick readme under the "Display" section.

How does Django determine if an uploaded image is valid?

I'm trying to add images to my models in my Django app.
models.py
class ImageMain(models.Model):
"""This is the Main Image of the product"""
product = models.ForeignKey(Product)
photo = models.ImageField(upload_to='products')
In development mode, every time I try to upload the image via Django admin, I keep getting:
Upload a valid image. The file you uploaded was either not an image or a corrupted image.
The jpg I'm trying to upload can be viewed with os X Preview so it would seem to be valid.
It seems the problem is Python Imaging Library doesn't recognize it as an image. Why would that be happening with a valid image?
PIL is installed, verified via the Django shell.
According to Django's source code. Those three lines are responsible for verifying images:
from PIL import Image
trial_image = Image.open(file)
trial_image.verify()
The image type could be unsupported by PIL. Check the list of supported formats here
Did you try uploading image format like gif or png? It might be that your PIL was not built with the jpeg lib properly. I had a similar issue with Django on Ubuntu. If you have ever seen the error message decoder jpeg not available, check this link. Relevant line from the link:
$ cd libImaging
$ ./configure --with-jpeg=/somelib/lib --with-zlib=/somelib/lib
I looked into the Django source, in django/forms/fields.py, in the ImageField class. Django actually does use PIL to determine when an image is valid.

Categories

Resources