Home > Article > Backend Development > How to scale and rotate images using Python
How to use Python to scale and rotate images
Introduction: Today, we often use images to enrich our web design, mobile applications, social media, etc. Scenes. In image processing, scaling and rotation are two common requirements. Python, as a scripting language and powerful image processing tool, provides many libraries and methods to handle these tasks. This article will introduce how to use Python to scale and rotate images, and provide code examples.
1. Zooming pictures
Zooming pictures is one of the basic operations to adjust the size of an image. It is often used to adjust the width, height or overall proportion of the picture. In Python, we can use the Pillow library for image processing.
First, we need to install the Pillow library. Open a command line window and enter the following command to install:
pip install pillow
After the installation is complete, we can use the following code example to zoom an image:
from PIL import Image # 打开原图片 image = Image.open("image.jpg") # 设置缩放尺寸 width = 800 height = 600 # 缩放图片 resized_image = image.resize((width, height)) # 保存缩放后的图片 resized_image.save("resized_image.jpg")
In the code example, we first use # The ##Image.open() method opens the original image, and then uses the
resize() method to scale the image to the specified size. Finally, use the
save() method to save the scaled image.
from PIL import Image # 打开原图片 image = Image.open("image.jpg") # 设置旋转角度 angle = 45 # 旋转图片 rotated_image = image.rotate(angle) # 保存旋转后的图片 rotated_image.save("rotated_image.jpg")In the above code example, we first open the original image using the
Image.open() method , and then use the
rotate() method to rotate the image to the specified angle. Finally, use the
save() method to save the rotated image.
from PIL import Image # 打开原图片 image = Image.open("image.jpg") # 设置缩放尺寸 width = 800 height = 600 # 设置旋转角度 angle = 45 # 缩放图片 resized_image = image.resize((width, height)) # 旋转图片 rotated_image = resized_image.rotate(angle) # 保存缩放和旋转后的图片 rotated_image.save("resized_and_rotated_image.jpg")In the above code example, we first use the
Image.open() method to open the original image, and then use
resize() method resizes the image to the specified size. Next, we use the
rotate() method to rotate the scaled image to the specified angle. Finally, use the
save() method to save the scaled and rotated image.
The above is the detailed content of How to scale and rotate images using Python. For more information, please follow other related articles on the PHP Chinese website!