avatarBetter Everything

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

2967

Abstract

</div> </div> </a> </div><h2 id="ef1a">Using the Pillow package</h2><p id="4ccd">To be able to easily work with images we will use the Pillow package. After installing Pillow we can easily import the <code>Image</code> class like this: <code>from PIL import Image</code></p><p id="6724">The pip install command is: <code>pip install Pillow</code></p><p id="33df">To learn more about Python packages and how to install them you can read my article:</p><div id="2264" class="link-block"> <a href="https://readmedium.com/the-power-of-python-packages-and-how-to-install-them-using-pip-7f33fe2a4952"> <div> <div> <h2>The power of Python packages and how to install them using pip</h2> <div><h3>3 examples of what Python packages are and why they are so poweful and how you can install them using pip.</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*NyPsaR6JnmahvGbuO9oq7w.jpeg)"></div> </div> </div> </a> </div><h2 id="b308">Writing the code</h2><p id="1ae4">The first step is to open the image in Python by passing the filepath to the <code>open</code> method of the <code>Image</code> class:</p><p id="ad07"><code>image = Image.open('In/'+filename)</code></p><p id="f4bb">We will immediately save the opened image without making any changes to it. But first we need to determine the new filename.</p><p id="9f19">The new filename can be build by removing the file extension and adding a new one:</p><p id="2865"><code>new_file_name = filename.split('.')[0]+'.'+type</code></p><p id="7988">Based on the file extension of the new file, the image will be formatted correctly in the new file type when saved:</p><p id="aa16"><code>image.save('Out/'+new_file_name)</code></p><h2 id="f0ae">Project Setup</h2><p id="4af8">Maybe you noticed the directories (file folders) used in the file paths.</p><p id="ecb2">The project folder has the Python file and 2 directories. The first directory is called <code>In</code> and is where the images are placed. And the second is called <code>Out</code>, which is where the script will save the converted images.</p><h2 id="9fc7">Converting our code to a function</h2><p id="cc01">We will make a function called <code>convert_image_type</code> that takes a <code>filename</code> and <code>type</code> as arguments.</p><p id="1e58">And we include a try-except statement to notify us in case something goes wrong. The <code>except</code> clause is only carried out when an error occurs in the <code>try</code> clause.</p><div id="2cdb"><pre><span class="hljs-keyword">from</span> PIL <span class="hljs-keyword">import</span> Image

<span class="hljs-keyword">def</span> <span class="hljs-title function_">convert_image_type</span>(<span class="hljs-

Options

params">filename,<span class="hljs-built_in">type</span></span>): <span class="hljs-keyword">try</span>: image = Image.<span class="hljs-built_in">open</span>(<span class="hljs-string">'In/'</span>+filename) new_file_name = filename.split(<span class="hljs-string">'.'</span>)[<span class="hljs-number">0</span>]+<span class="hljs-string">'.'</span>+<span class="hljs-built_in">type</span> image.save(<span class="hljs-string">'Out/'</span>+new_file_name) <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e: <span class="hljs-built_in">print</span>(<span class="hljs-string">'Something went wrong, check the filename and type extension:'</span>) <span class="hljs-built_in">print</span>(e) <span class="hljs-built_in">print</span>(filename,<span class="hljs-built_in">type</span>)</pre></div><p id="ecd4"><i>Test 1</i> Now we will test the function in a scenario that should work.</p><p id="d816"><code>convert_image_type('good_app.png','ico')</code> results in…</p><p id="7996">Success! An ico file appears in the <code>out</code> directory. That file was also successfully used when creating a desktop application.</p><p id="5d38">If we pass a wrong or non-existing filename or filetype the function will print a message.</p><p id="34ba"><i>Test 2 </i><code>convert_image_type('good_app.png','pico')</code> results in:</p><div id="6fd0"><pre>Something went wrong, check the filename <span class="hljs-keyword">and</span> <span class="hljs-built_in">type</span> extension: unknown file extension: .pico good_app.png pico</pre></div><p id="e6cb"><i>Test 3 </i><code>convert_image_type('bad_app.png','ico')</code> results in:</p><div id="f3b6"><pre>Something went wrong, check the filename <span class="hljs-keyword">and</span> <span class="hljs-built_in">type</span> extension: [Errno <span class="hljs-number">2</span>] No such file <span class="hljs-keyword">or</span> directory: <span class="hljs-string">'In/bad_app.png'</span> bad_app.png ico</pre></div><h1 id="2ee9">Thank you for reading!</h1><p id="fa9f">You can <b>get full access to all my posts by joining Medium</b>. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium:</p><div id="ba8f" class="link-block"> <a href="https://medium.com/@BetterEverything/membership"> <div> <div> <h2>Join Medium with my referral link — Better Everything</h2> <div><h3>Read every story from Better Everything (and thousands of other writers on Medium). Your membership fee directly…</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*aa4Y_6MHVoY6Wl-9)"></div> </div> </div> </a> </div></article></body>

Converting Images to other File Types — Small Python projects #3

Images can be saved on computers in many different file types. Some examples are: PNG, JPG or ICO.

We will write a program that can convert images to other file types. Image by catalyststuff on Freepik

Different scenarios might require different file types. So today we will write a simple Python program that can convert a file to a specified image type.

This article is part of a series about small Python projects, you can find the previous episode here:

Introducing our test subject

As a test we will try to convert the following PNG image good_app.png to an image of type ICO:

The PNG image good_app.png which we will convert to an ico file. Source: own image.

An ICO file can be used as an icon for a desktop application for example.

To learn how to transform a Python file into a desktop application read:

Using the Pillow package

To be able to easily work with images we will use the Pillow package. After installing Pillow we can easily import the Image class like this: from PIL import Image

The pip install command is: pip install Pillow

To learn more about Python packages and how to install them you can read my article:

Writing the code

The first step is to open the image in Python by passing the filepath to the open method of the Image class:

image = Image.open('In/'+filename)

We will immediately save the opened image without making any changes to it. But first we need to determine the new filename.

The new filename can be build by removing the file extension and adding a new one:

new_file_name = filename.split('.')[0]+'.'+type

Based on the file extension of the new file, the image will be formatted correctly in the new file type when saved:

image.save('Out/'+new_file_name)

Project Setup

Maybe you noticed the directories (file folders) used in the file paths.

The project folder has the Python file and 2 directories. The first directory is called In and is where the images are placed. And the second is called Out, which is where the script will save the converted images.

Converting our code to a function

We will make a function called convert_image_type that takes a filename and type as arguments.

And we include a try-except statement to notify us in case something goes wrong. The except clause is only carried out when an error occurs in the try clause.

from PIL import Image

def convert_image_type(filename,type):
    try:
        image = Image.open('In/'+filename)
        new_file_name = filename.split('.')[0]+'.'+type
        image.save('Out/'+new_file_name)
    except Exception as e:
        print('Something went wrong, check the filename and type extension:')
        print(e)
        print(filename,type)

Test 1 Now we will test the function in a scenario that should work.

convert_image_type('good_app.png','ico') results in…

Success! An ico file appears in the out directory. That file was also successfully used when creating a desktop application.

If we pass a wrong or non-existing filename or filetype the function will print a message.

Test 2 convert_image_type('good_app.png','pico') results in:

Something went wrong, check the filename and type extension:
unknown file extension: .pico
good_app.png pico

Test 3 convert_image_type('bad_app.png','ico') results in:

Something went wrong, check the filename and type extension:
[Errno 2] No such file or directory: 'In/bad_app.png'
bad_app.png ico

Thank you for reading!

You can get full access to all my posts by joining Medium. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium:

Python
Software Development
Programming
File Conversion
Data
Recommended from ReadMedium