analitics

Pages

Sunday, July 24, 2022

Python 3.11.0a7 : image conversions in Python.

Image processing is very important in development, therefore also in python.
The image processing packages used in python have undergone changes over time.
Pillow and PIL cannot co-exist in the same environment. Before installing Pillow, please uninstall PIL.
Pillow higher than version 10 no longer supports import Image. Please use from PIL import Image instead.
Pillow higher than version 2.1.0 no longer supports import _imaging. Please use from PIL.Image import core as _imaging instead.
Although the image formats are old compared to the newer ones in vector format, they are preferred depending on the field of work.
You can see all of these file image formats on the official python package.
First, the basic installation start with upgrade the pip tool:
C:\PythonProjects\ConvertImages>python -m pip install --upgrade pip
Requirement already satisfied: pip in c:\python311alpha\lib\site-packages (22.1.
2)
Collecting pip
  Downloading pip-22.2-py3-none-any.whl (2.0 MB)
     ---------------------------------------- 2.0/2.0 MB 3.3 MB/s eta 0:00:00
Installing collected packages: pip
  Attempting uninstall: pip
    Found existing installation: pip 22.1.2
    Uninstalling pip-22.1.2:
      Successfully uninstalled pip-22.1.2
Successfully installed pip-22.2
Secondary, the install of the Pillow python package:
C:\PythonProjects\ConvertImages>python  -m pip install --upgrade Pillow
Collecting Pillow
  Downloading Pillow-9.2.0-cp311-cp311-win_amd64.whl (3.3 MB)
     ---------------------------------------- 3.3/3.3 MB 4.0 MB/s eta 0:00:00
Installing collected packages: Pillow
Successfully installed Pillow-9.2.0
I have a webp image here that I have scaled to smaller sizes and that I will test its conversion from webp format to png format.
The image is named waterski2 and I'm using the 3.11.0a7 python version.
Let's see the source code:
from PIL import Image

# open the image file WEBP
image = Image.open('waterski2.webp')

# show the image 
image.show()

# convert the image to RGB color
image = image.convert('RGB')

# save PNG RGB image
image.save('waterski2_RGB_PNG.png', 'png')

# save JPG RGB image
image.save('waterski2_RGB_JPG.jpg', 'jpeg')

# open the image file JPG
image_jpg = Image.open('waterski2_RGB_JPG.jpg')

# convert the image to RGB color
image_rgb_jpg = image_jpg.convert('RGB')

# save PNG RGB image from JPG
image_rgb_jpg.save('new-image_RGB_PNG_from_JPG.png', 'png')

#same process of conversion to WEBP file type
# from png image
image = Image.open('waterski2_RGB_PNG.png')
image = image.convert('RGB')
image.save('new-image_RGB_WEBP_from_png.webp', 'webp')
# from jpg image
image = Image.open('waterski2_RGB_JPG.jpg')
image = image.convert('RGB')
image.save('new-image_RGB_WEBP_from_jpg.webp', 'webp')
Here is a screenshot with these converted images and the processed image.