How To Change Image Width And Height In Python

In this concept, we will learn how to change the width and height of an image simply and easily.

Generally, People prefer to change the width and height of an image so that the appearance of the image will be clear and the image will have enough quality. Also, by reducing the pixels of the image, the process of sharing becomes easier.

Changing the width and height of an image in Python

You can use any IDE or any kind of code editor like Python IDE, or Visual Studio Code for writing, running, and displaying the output of your Python code.

Let’s have a look at the following example:

from PIL import Image
  • Here. PILĀ  stands for Python Imaging Library helps users deal with operations(like making changes to an image and saving it) related to different kinds of image formats(jpg, png etc..).
  • If you can’t find PIL in your system, you can simply install it from the command “pip install pillow”.
  • Basically, Here we are importing the image module from PIL.

The following code as follows:

pic = Image.open("Pictures/Maredumilli.jpg")
w = 900
h = 1100
  • Image Module consists of various kinds of methods like as you can see in the above code which is open(). In the open() method we will provide the path of the image which we want to open, Where I have mentioned the path of my image and we store it in the user defined object which is here “pic”.
  • Next, We declare two objects w – width, h – height of the image and provide the values which we want for the image which we are changing.

The code follows as:

pic = pic.resize((w,h),Image.Resampling.LANCZOS)
pic.save("pictures/Maredumilli2.jpg")
pic.show()
  • Here, we are going to use resize() method were we have to mention the w and h objects for resizing the image.
  • There are chances of getting ValueError if you didn’t mention the resampling filter which is LANCZOS used for getting the more high quality of images while resizing the images.
  • Next, We will be using the save() method where we will specify the path for saving the changed image. Also, it will appear along with the original image in the same folder.
  • At last, we will display the image using show() method.

Let’s focus on the Output:

https://drive.google.com/folderview?id=1nU95LIM_Dg1oKrZD7gFbR1OeJwMfZtS1

In the Above link you can observe the difference between the original image to the changed image according to width and height.

 

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top