I'm resizing images in python using Pillow
image = Image.open("image_file.jpg")
print(image.format) # Prints JPEG
resized_image = image.resize([100,200],PIL.Image.ANTIALIAS)
print(resized_image.format) # Prints None!!
Why does resized_image.format Hold a None Value?
And How can i retain the format when resizing using pillow?
Because Image.resize creates a new Image object (resized copy of the image) and for any images when creating by the library itself (via a factory function, or by running a method on an existing image), the "format" attribute is set to None.
If you need the format attribute you still can to do this:
image = Image.open("image_file.jpg") #old image object
resized_image = image.resize([100,200],PIL.Image.ANTIALIAS)
resized_image.format = image.format # original image extension
Read the docs
As stated in the documentation:
The file format of the source file. For images created by the library itself (via a factory function, or by running a method on an existing image), this attribute is set to None.
You can specify the format on save:
image.save(fp, 'JPEG')
You can save the resized images with save comments
resized_image.save("New_image.png")
It will save into your current directory.
If you want to see in the python console itself you have to run
resized_image.show()
Related
I made an API call to convert an image into a thumbnail version of itself, and that returned a Generator object. But I don't know how to save that object as an image on my local machine.
I get from the documentation of the API that a "successful response contains the thumbnail image binary", but I don't know how to access it. I was thinking, so I need to convert the binary into a string or list and then convert that into an image by using the Image class from PIL?
I don't know the best way to do it. I know Generators are just iterators that save state, but that doesn't mean much when it comes to image data being in it and accessing the data so that I have a saved image in my local folder.
Here is my code:
computervision_client = ComputerVisionClient(endpoint, CognitiveServicesCredentials(subscription_key))
# Get a local image
local_image_path_thumb = "resources\\objects.jpg"
local_image_thumb = open(local_image_path_objects, "rb")
print("Generating thumbnail from a local image...")
# Call the API with a local image, set the width/height if desired (pixels)
# Returns a Generator object, a thumbnail image binary.
thumb_local = computervision_client.generate_thumbnail_in_stream(100, 100, local_image_thumb, True)
# Save the thumbnail to your local root folder of this project.
# Save to here, somehow: "\\resources\\thumb_local.jpg"
print("Thumbnail saved to local folder.")
Here is the API documentation for the function generate_thumbnail_in_stream.
with open("output_file.png", "wb") as fp:
for chunk in thumb_local:
fp.write(chunk)
The pillow package has a method called Image.putalpha() which is used to add or change the alpha channel of an image.
I tried to play with this method and found that I can not change the background color of an image. The original image is
This is my code to add alpha to it
from PIL import Image
im_owl = Image.open("owl.jpg")
alpha = Image.new("L", im_owl.size, 50)
im_owl.putalpha(alpha)
im_owl.show()
The produced image is nothing different from the original image. I have tried with different value of alpha and see no difference.
What could have been wrong?
try to save the image and see it.
I am also not able to see the image directly from
im_owl.show()
but when I saved it
im_owl.save()
I am able to see the image changed.
Try using
im_owl.save("alphadOwl.png")
And then view the saved image. It would seem that the alpha channel isn't applied to bmp or jpg files. It is a bmp file that gets displayed with im.show()
(For the record, I'm on a mac, I don't know if im.show() uses different applications on other devices).
As #sanyam and #Pam have pointed out, we can save the converted image and it shows correctly. This is because on Windows, images are saved as temporary BMP file before they are shown using the system default image viewer, as per the PIL documentation:
Image.show(title=None, command=None)
Displays this image. This method is mainly intended for debugging purposes.
On Unix platforms, this method saves the image to a temporary PPM file, and calls
either the xv utility or the display utility, depending on which one can be found.
On macOS, this method saves the image to a temporary BMP file, and opens it with
the native Preview application.
On Windows, it saves the image to a temporary BMP file, and uses the standard BMP
display utility to show it (usually Paint).
To fix this issue, we can patch the Pillow code to use PNG format as default. First, we need to find the root of Pillow package:
import PIL
print(PIL.__path__)
On my system, the output is:
[’D:\Anaconda\lib\site-packages\PIL’]
Go to this directory and open the file ImageShow.py. I add the following code after the line register(WindowsViewer):
class WindowsPNGViewer(Viewer):
format = "PNG"
def get_command(self, file, **options):
return ('start "Pillow" /WAIT "%s" '
'&& ping -n 2 127.0.0.1 >NUL '
'&& del /f "%s"' % (file, file))
register(WindowsPNGViewer, -1)
After that, I can show the image with alpha channel correctly.
References
https://github.com/python-pillow/Pillow/issues/3695
When i open an image in image viewer the displayed image name is wrong (not the same as loaded image). Orginal image = 'image.PNG', name in image viewer='tmpy4uvijg0.BMP' (the new name always changeds, see in image below)
from PIL import Image
imName='image.PNG'
try:
with Image.open(imName) as im:
print(imName)
im.show()
except IOError:
pass
image.png
new image
What do i wrong? Why is the name not the same?
It is because the show method save the image to a temporary file, as say in the documentation:
Displays this image. This method is mainly intended for
debugging purposes.
On Unix platforms, this method saves the image to a temporary
PPM file, and calls the xv utility.
On Windows, it saves the image to a temporary BMP file, and uses
the standard BMP display utility to show it (usually Paint).
:param title: Optional title to use for the image window,
where possible.
:param command: command used to show the image
You can try to change the title by passing a string in parameter to show.
I want to generate a barcode image. So, I used elaphe package. It works correctly but it returns PIL.EPSImageFile instance. I don't know how I can convert it to image format like SVG, PNG or JPG.
The code I have written is:
barcode('code128', 'barcodetest')
And it returns:
<PIL.EpsImagePlugin.EpsImageFile image mode=RGB size=145x72 at 0x9AA47AC>
How can I convert this instance to image?
Actually I think my question is wrong but I don't know how to explain it well!
Simply save that file object to something with a .png or .jpg filename:
bc = barcode('qrcode',
'Hello Barcode Writer In Pure PostScript.',
options=dict(version=9, eclevel='M'),
margin=10, data_mode='8bits')
bc.save('yourfile.jpg')
or state the format explicitly:
bc.save('yourfile.jpg', 'JPEG')
PIL will then convert the image to the correct format.
Note that the PIL EPS module uses the gs command from the Ghostscript project to do it's conversions, you'll need to have it installed for this to work.
More specifically, I want to change the filetype of an image uploaded through a Django ImageField.
My current thinking is to created a custom ImageField and overwrite the save method to manipulate the file.
I've having trouble getting an in memory file to because a PIL Image instance.
Thanks for the help.
Have you tried StringIO ?
see the docs http://effbot.org/imagingbook/introduction.htm#more-on-reading-images
#Reading from a string
import StringIO
im = Image.open(StringIO.StringIO(buffer))
Note that Django's ImageField inherits the open method from FieldFile. This returns a stream object that can be passed to PIL's Image.open (the standard factory method for creating Image objects from an image stream):
stream = imagefield.open()
image = Image.open(stream)
stream.close()
# ... and then save image with: image.save(outfile, format, options)
See PIL Image documentation.