Pillow Basic
\\
After installing the Pillow library, we need to import the necessary modules:\\
\\
# Import module from PIL import Image, ImageFilter, ImageEnhance, ImageDraw, ImageFontimport os\\
Test image (download to local for testing):\\
\\
[!(#)](#)\\
\\
### Instance\\
\\
The following complete example demonstrates the following operations:\\
\\
1. **Open and display image basic information**\\
* Format, size, mode, etc.\\
\\
2. **Resize image**\\
* Resize image to specified dimensions\\
\\
3. **Crop image**\\
* Extract specific region from original image\\
\\
4. **Rotate image**\\
* Rotate 45 degrees and keep the complete image\\
\\
5. **Flip image**\\
* Horizontal and vertical flip\\
\\
6. **Convert color mode**\\
* Convert color image to grayscale\\
\\
7. **Apply filters**\\
* Blur, edge enhancement, contour and other effects\\
\\
8. **Adjust image properties**\\
* Brightness, contrast and sharpness adjustment\\
\\
9. **Add text**\\
* Draw text on image\\
\\
10. **Merge images**\\
* Simple image stitching\\
\\
11. **Save in different formats and quality**\\
* PNG, BMP and different quality JPEG\\
\\
## Instance\\
\\
"""\\
\\
Python Pillow Image Basic Operations Tutorial\\
\\
Test image used: tiger.jpeg\\
\\
"""\\
\\
from PIL import Image, ImageFilter, ImageEnhance, ImageDraw, ImageFont\\
\\
import os\\
\\
def main():\\
\\
# Ensure there is an output folder in our working directory\\
\\
output_dir ="output"\\
\\
if not os.path.exists(output_dir):\\
\\
os.makedirs(output_dir)\\
\\
# 1. Open Image\\
\\
print("1. Open Image")\\
\\
try:\\
\\
img = Image.open("tiger.jpeg")\\
\\
print(f"Successfully opened image - format: {img.format}, Size: {img.size}, Mode: {img.mode}")\\
\\
except Exception as e:\\
\\
print(f"Cannot open image: {e}")\\
\\
return\\
\\
# 2. Display basic image information\\
\\
print("n 2. Basic Image Information")\\
\\
print(f"Image Format: {img.format}")\\
\\
print(f"Image size (Width x Height): {img.size}")\\
\\
print(f"Image mode: {img.mode}")\\
\\
# 3. Resize Image\\
\\
print("n 3. Resize Image")\\
\\
resized_img = img.resize((400,300))\\
\\
resized_img.save(f"{output_dir}/resized_tiger.jpg")\\
\\
print("Saved the resized image")\\
\\
# 4. Crop Image\\
\\
print("n 4. Crop Image")\\
\\
# Crop area (left, on, Right, lower)\\
\\
width, height = img.size\\
\\
crop_area =(width//4, height//4,3*width//4,3*height//4)# Crop Center Region\\
\\
cropped_img = img.crop(crop_area)\\
\\
cropped_img.save(f"{output_dir}/cropped_tiger.jpg")\\
\\
print(f"Cropped image area {crop_area} and save")\\
\\
# 5. Rotate Image\\
\\
print("n 5. Rotate Image")\\
\\
rotated_img = img.rotate(45, expand=True)# Rotate 45 degrees, expand=True Keep the entire image\\
\\
rotated_img.save(f"{output_dir}/rotated_tiger.jpg")\\
\\
print("Saved Rotated Image")\\
\\
# 6. Flip image\\
\\
print("n 6. Flip image")\\
\\
# Flip Horizontally\\
\\
h_flipped = img.transpose(Image.FLIP_LEFT_RIGHT)\\
\\
h_flipped.save(f"{output_dir}/horizontal_flip_tiger.jpg")\\
\\
# Vertical flip\\
\\
v_flipped = img.transpose(Image.FLIP_TOP_BOTTOM)\\
\\
v_flipped.save(f"{output_dir}/vertical_flip_tiger.jpg")\\
\\
print("Saved the horizontally and vertically flipped image")\\
\\
# 7. Convert color mode\\
\\
print("n 7. Convert color mode")\\
\\
grayscale_img = img.convert('L')# Convert to grayscale image\\
\\
grayscale_img.save(f"{output_dir}/grayscale_tiger.jpg")\\
\\
print("Saved the grayscale image")\\
\\
# 8. Apply filter\\
\\
print("n 8. Apply filter")\\
\\
# Blur Filter\\
\\
blurred_img = img.filter(ImageFilter.BLUR)\\
\\
blurred_img.save(f"{output_dir}/blurred_tiger.jpg")\\
\\
# Edge Enhancement\\
\\
edge_img = img.filter(ImageFilter.EDGE_ENHANCE)\\
\\
edge_img.save(f"{output_dir}/edge_enhanced_tiger.jpg")\\
\\
# Contour Filter\\
\\
contour_img = img.filter(ImageFilter.CONTOUR)\\
\\
contour_img.save(f"{output_dir}/contour_tiger.jpg")\\
\\
print("Saved image with different filters applied")\\
\\
# 9. Adjust brightness, contrast, and sharpness\\
\\
print("n 9. Adjust image properties")\\
\\
# increaseBrightnessdegree\\
\\
brightness = ImageEnhance.Brightness(img)\\
\\
bright_img = brightness.enhance(1.5)# Brightness increased by 50%\\
\\
bright_img.save(f"{output_dir}/brighter_tiger.jpg")\\
\\
# Increase contrast\\
\\
contrast = ImageEnhance.Contrast(img)\\
\\
contrast_img = contrast.enhance(1.5)# Contrast increased by 50%\\
\\
contrast_img.save(f"{output_dir}/contrast_tiger.jpg")\\
\\
# Increase sharpness\\
\\
sharpness = ImageEnhance.Sharpness(img)\\
\\
sharp_img = sharpness.enhance(2.0)# Sharpness increased by 100%\\
\\
sharp_img.save(f"{output_dir}/sharper_tiger.jpg")\\
\\
print("Saved the image after adjusting brightness, contrast, and sharpness")\\
\\
# 10. Add Text\\
\\
print("n 10. Add Text")\\
\\
# Create a copy for drawing\\
\\
text_img = img.copy()\\
\\
draw = ImageDraw.Draw(text_img)\\
\\
# Try using the system font, fallback to default if it fails\\
\\
try:\\
\\
# Different font paths may be required for different operating systems\\
\\
# WindowsFont path example\\
\\
font = ImageFont.truetype("arial.ttf",36)\\
\\
except IOError:\\
\\
font = ImageFont.load_default()\\
\\
# Add text on the image\\
\\
draw.text((10,10),"Tiger", fill=(255,255,255), font=font)\\
\\
text_img.save(f"{output_dir}/text_tiger.jpg")\\
\\
print("Saved image with text added")\\
\\
# 11. Merge ImagesοΌSimple stitching)\\
\\
print("n 11. Merge Images")\\
\\
# Create a new image, Width is twice the original, Height is the same\\
\\
merged_img = Image.new('RGB',(width*2, height))\\
\\
# Place the original image on the left\\
\\
merged_img.paste(img,(0,0))\\
\\
# place/putgraydegreeimageplace onRightEdge\\
\\
merged_img.paste(grayscale_img.convert('RGB'),(width,0))\\
\\
merged_img.save(f"{output_dir}/merged_tiger.jpg")\\
\\
print("Saved merged image")\\
\\
# 12. Save as a different format\\
\\
print("n 12. Save as a different format")\\
\\
img.save(f"{output_dir}/tiger.png")# PNGFormat\\
\\
img.save(f"{output_dir}/tiger.bmp")# BMPFormat\\
\\
# Save as JPEG, set quality\\
\\
img.save(f"{output_dir}/tiger_high_quality.jpg", quality=95)# HighQuality\\
\\
img.save(f"{output_dir}/tiger_low_quality.jpg", quality=10)# Low quality\\
\\
print("Saved image in different formats and qualities")\\
\\
print("n All operations completed! The processed image is saved in 'output' in the folder.")\\
\\
if __name__ =="__main__":\\
\\
main()\\
\\
The code uses a structured approach, with clear comments for each operation. All processed images will be saved in the output directory for easy viewing and comparing effects.\\
\\
**Usage:**\\
\\
* Make sure you have the tiger.jpeg image in the same directory as the code\\
* Run the code, and various processed images will be generated in the output folder\\
* Check the different processing effects based on the output information\\
\\
If the above code executes successfully, the terminal output is:\\
\\
!(
YouTip