PyQt5 - Load JPEG-compressed image to QImage - python-3.x

I have an application that displays images, using QtGui.QImage. To save space, I changed the GeoTiff compression from LZW to JPEG, but now I get the following error:
foo: JPEG compression support is not configured.
foo: Sorry, requested compression method is not configured.
I have not found anything how I can configure PyQt to understand that type of compression. Do I need a specific build or can I set it somewhere?
Using Python 3.10 with PyQt5.15

Thanks to the comment of #musicamante, the issue could be solved simply by using:
from PIL.ImageQt import ImageQt
my_q_image = ImageQt(image_path)
Then, my_q_image acts exactly like a QImage.
Important reminder though, which I found while investigating this: PyQt5 support from PIL ends in July 2023!

Related

PySide6: fail to load "jpg" format in QPixmap

I'm trying to load "jpg" picture on the QLabel in PySide6. So I used this:
mypic = QPixmap()
mypic.load("./test.jpg")
self.ui.mylabel.setPixmap(QPixmap(mypic))
However, I found there is empty in mylabel. When I debug in this program, I found that my pic is null (even after it loads the image file).
So I wonder if the jpg is not automatically supported in PySide6.
As I checked the documention of PySide6, it illustrates that the default supporting image formats include "jpg".
enter image description here
As I print the supportedImageFormats using:
print(QtGui.QImageReader.supportedImageFormats())
It returns with this:
[PySide6.QtCore.QByteArray(b'bmp'), PySide6.QtCore.QByteArray(b'pbm'), PySide6.QtCore.QByteArray(b'pgm'), PySide6.QtCore.QByteArray(b'png'), PySide6.QtCore.QByteArray(b'ppm'), PySide6.QtCore.QByteArray(b'xbm'), PySide6.QtCore.QByteArray(b'xpm')]
I found it does not include the "jpg" format by default!
Then I searched a lot of solutions, I found that this can solve my problem: add one line of code to introduce the "imageformats" plugins in PySide6 folder.
app.addLibraryPath(os.path.join(os.path.dirname(QtCore.__file__), "plugins"))
Here I printed the os.path.dirname(QtCore.__file__), and found it was my PySide6 folder.
I checked the plugins folder, and found the inner imageformats folder, and found these dlls:
enter image description here
It seems that the jpg format is supported here. So when I add the plugin path, it can solve my problem. But it still confuses me that why I should add the plugin path (The official documentation implies that this format is supported by default!).
I wonder if there is a more convincing solution because adding one line of code in my program every time seems clumsy. Or if I left out something. I sincerely want to get your help. Thank you!

Convert PIL.Image to/from Gtk.Picture/Gtk.Image in gtk4

I do RGBA image manipulation in PIL(low) and would like to display the resulting image in a gtk4 application. For that, I'd need a seamless PIL.Image <--> Gtk.Picture/Gtk.Image converter. I'd like to avoid using temporary files at all cost. I found helpful hints here and here but was wondering if there was anything more convenient in gtk4?
As of GTK 4.4, this seems to work best:
buffer = GLib.Bytes.new(pil_image.tobytes())
gdata = GdkPixbuf.Pixbuf.new_from_bytes(buffer, GdkPixbuf.Colorspace.RGB, True, 8, pil_image.width, pil_image.height, len(pil_image.getbands())*pil_image.width)
gtk_image = Gtk.Image.new_from_pixbuf(gdata)
Once GTK 4.6+ becomes ubiquitous, GdkPixbuf should be replaced with GdkTexture, via Gdk.Texture.new_from_bytes().

Is there any way I can save the plot as .jpg [duplicate]

I am using matplotlib (within pylab) to display figures. And I want to save them in .jpg format. When I simply use the savefig command with jpg extension this returns :
ValueError: Format "jpg" is not supported.
Supported formats: emf, eps, pdf, png, ps, raw, rgba, svg, svgz.
Is there a way to perform this ?
You can save an image as 'png' and use the python imaging library (PIL) to convert this file to 'jpg':
import Image
import matplotlib.pyplot as plt
plt.plot(range(10))
plt.savefig('testplot.png')
Image.open('testplot.png').save('testplot.jpg','JPEG')
The original:
The JPEG image:
To clarify and update #neo useful answer and the original question. A clean solution consists of installing Pillow, which is an updated version of the Python Imaging Library (PIL). This is done using
pip install pillow
Once Pillow is installed, the standard Matplotlib commands
import matplotlib.pyplot as plt
plt.plot([1, 2])
plt.savefig('image.jpg')
will save the figure into a JPEG file and will not generate a ValueError any more.
Contrary to #amillerrhodes answer, as of Matplotlib 3.1, JPEG files are still not supported. If I remove the Pillow package I still receive a ValueError about an unsupported file type.
Just install pillow with pip install pillow and it will work.
I just updated matplotlib to 1.1.0 on my system and it now allows me to save to jpg with savefig.
To upgrade to matplotlib 1.1.0 with pip, use this command:
pip install -U 'http://sourceforge.net/projects/matplotlib/files/matplotlib/matplotlib-1.1.0/matplotlib-1.1.0.tar.gz/download'
EDIT (to respond to comment):
pylab is simply an aggregation of the matplotlib.pyplot and numpy namespaces (as well as a few others) jinto a single namespace.
On my system, pylab is just this:
from matplotlib.pylab import *
import matplotlib.pylab
__doc__ = matplotlib.pylab.__doc__
You can see that pylab is just another namespace in your matplotlib installation. Therefore, it doesn't matter whether or not you import it with pylab or with matplotlib.pyplot.
If you are still running into problem, then I'm guessing the macosx backend doesn't support saving plots to jpg. You could try using a different backend. See here for more information.
Matplotlib can handle directly and transparently jpg if you have installed PIL. You don't need to call it, it will do it by itself. If Python cannot find PIL, it will raise an error.
I'm not sure about all versions of Matplotlib, but in the official documentation for v3.5.0 savfig allows you to pass settings through to the underlying Pillow library which anyway does the image saving. So if you want a jpg with specific compression settings for example:
import matplotlib.pyplot as plt
plt.plot(...) # Plot stuff
plt.savefig('filename.jpg', pil_kwargs={
'quality': 20,
'subsampling': 10
})
This should give you a highly compressed jpg as the output.
Just for completeness, if you also want to control the quality (i.e. compression level) of the saved result, it seems to get a bit more complicated, as directly passing plt.savefig(..., quality=5) does not seem to have an effect on the output size and quality. So, on the one hand, one could either go the way of saving the result as a png first, then reloading it with PIL, then saving it again as a jpeg, using PIL's quality parameter – similar to what is suggested in Yann's answer.
On the other hand, one can avoid this deviation of loading and saving, by using BytesIO (following the answer to this question):
from io import BytesIO
import matplotlib.pyplot as plt
from PIL import Image
buf = BytesIO()
plt.plot(...) # Plot something here
plt.savefig(buf)
Image.open(buf).convert("RGB").save("testplot.jpg", quality=5)

Encoding error using google adwords api

I am using the google adwords api. Currenlty my only code is:
from googleads import adwords
adwords_client = adwords.AdWordsClient.LoadFromStorage()
This results in an error displaying Your default encoding, cp1252, is not UTF-8. Please run this script with UTF-8 encoding to avoid errors.
I am using Python 3.6, which should be UTF-8 by default. What is the source of this error/how is it avoided?
It turns out that this is actually a warning emitted by googleads whenever the default encoding returned by locale.getdefaultlocale() is not UTF-8.
If your script runs without issues, I feel that you can safely ignore it. Otherwise it might be worth a try to set a different locale at the beginning of your code:
import locale
locale.setlocale(locale.LC_ALL, NEW_LOCALE)
I take it that you are running Windows, so I'm not sure what the proper locale definitions are. On Linux, you could use en_US.UTF-8, but that's probably not going to work for you.
Try importing the _locale module.
import _locale
_locale._getdefaultlocale = (lambda *args: ['en_US', 'UTF-8'])

How to import an existing PDF file in node.js

I am working on import routines for node, so far I can import text nodes from a PDF using pdf2json, this works well, but doesn't work on PDF's that are image based and contain no text.
So I downloaded pdf2img, however there are plenty of issues with this module, the one I have now is that after running it, I get a lot of 0 byte png files created, no content and an error message:
/docfire/node_modules/gm/lib/command.js:228
proc.stdin.once('error', cb);
^
TypeError: Cannot read property 'once' of undefined
at gm._spawn (/docfire/node_modules/gm/lib/command.js:228:15)
at /docfire/node_modules/gm/lib/command.js:140:19
at series (/docfire/node_modules/array-series/index.js:11:36)
at gm._preprocess
(/docfire/node_modules/gm/lib/command.js:177:5)
at gm.stream (/docfire/node_modules/gm/lib/command.js:138:10)
at convertPdf2Img (/docfire/node_modules/pdf2img/lib/pdf2img.js:93:6)
at /docfire/node_modules/pdf2img/lib/pdf2img.js:67:9
at /docfire/node_modules/async/lib/async.js:246:17
at /docfire/node_modules/async/lib/async.js:122:13
at _each (/docfire/node_modules/async/lib/async.js:46:13)
I've tried posting a issue on the GIT site for the module, but it looks like quite a few people are having exactly the same problem and there doesn't seem to be any activity regarding any fixes.
What I would ideally like is a way to extract text and images from a PDF for node.
I'm running on an iMAC running macOS Sierra v10.12.4
With node version 7.8.0, pdf2img 0.2.0, gm 1.23.0
You can try pdf-image npm package.
https://www.npmjs.com/package/pdf-image
Hope this helps.

Resources