If you are building a web application, a data processing pipeline, or a machine learning model, you might get a requirement to save images in Python while working with images. In this tutorial, I will explain several methods to save images in Python using different libraries with real examples. I will also show you how to save images to a folder in Python with complete code.
To save an image to a directory in Python using the Pillow library, first, import the Image module from Pillow and the os module. Open the image using Image.open('image_name.jpg'), define your target directory, and ensure it exists using os.makedirs(directory, exist_ok=True). Finally, save the image to the desired directory with image.save(os.path.join(directory, 'new_image_name.png')). This method ensures your image is saved efficiently and correctly in the specified folder.
Table of Contents
ToggleSave Images in PythonPython provides various libraries to save an image in Python. Let me show you each method with examples.
1. Using the Pillow LibraryThe Pillow library (PIL) is one of the most popular libraries for image processing in Python. It allows you to open, manipulate, and save images easily.
Example: Save an Image with Pillow LibraryLet me show you an example of saving an image in Python using this library.
from PIL import Image# Open an existing imageimage = Image.open('new_york_city.jpg')# Save the image in a different formatimage.save('new_york_city.png')In this example, we open an image named new_york_city.jpg and save it as new_york_city.png. This is particularly useful when you need to convert images between different formats.
Example: Save an Image to a Directory with Pillow LibraryLet’s see how to save an image to a specific directory in Python using the Pillow library.
from PIL import Imageimport os# Open an existing imageimage = Image.open('new_york_city.jpg')# Define the directorydirectory = 'images/'# Create directory if it doesn't existif not os.path.exists(directory):os.makedirs(directory)# Save the image to the directoryimage.save(os.path.join(directory, 'new_york_city.png'))In this example, we open an image named new_york_city.jpg and save it as new_york_city.png in the images/ directory. The os.makedirs function ensures that the directory exists before saving the image.
Check out How to Remove Background From Image in Python
2. Save Images with OpenCVOpenCV is another powerful library for image processing in Python. It is widely used in computer vision applications and provides a straightforward way to save images.
Let me show you some examples.
Example: Save an Image with OpenCVHere is an example of how to save an image with OpenCV.
import cv2# Read an imageimage = cv2.imread('los_angeles.jpg')# Save the imagecv2.imwrite('los_angeles_saved.jpg', image)In this example, we read an image named los_angeles.jpg and save it as los_angeles_saved.jpg. OpenCV is particularly efficient for real-time applications.
Example: Save an Image to a Directory with OpenCVLet me show you an example of saving an image to a folder using OpenCV in Python.
import cv2import os# Read an imageimage = cv2.imread('los_angeles.jpg')# Define the directorydirectory = 'saved_images/'# Create directory if it doesn't existif not os.path.exists(directory):os.makedirs(directory)# Save the image to the directorycv2.imwrite(os.path.join(directory, 'los_angeles_saved.jpg'), image)In this example, we read an image named los_angeles.jpg and save it as los_angeles_saved.jpg in the saved_images/ directory.
Check out Django Upload Image File
3. Download and Save Images from URLsSometimes, you might need to download images from the web and save them locally. Python’s requests library combined with shutil makes this task easy.
Let me show you an example to help you understand.
Example: Download and Save an ImageHere is an example of downloading and saving images from a URL in Python.
import requestsimport shutil# URL of the imageurl = 'https://example.com/san_francisco.jpg'# Send a GET requestresponse = requests.get(url, stream=True)# Save the imagewith open('san_francisco.jpg', 'wb') as out_file:shutil.copyfileobj(response.raw, out_file)del responseIn this example, we download an image from a URL and save it as san_francisco.jpg.
Example: Download and Save an Image to a FolderHere is an example of saving an image to a folder in Python.
import requestsimport shutilimport os# URL of the imageurl = 'https://example.com/san_francisco.jpg'# Define the directorydirectory = 'downloaded_images/'# Create directory if it doesn't existif not os.path.exists(directory):os.makedirs(directory)# Send a GET requestresponse = requests.get(url, stream=True)# Save the image to the directorywith open(os.path.join(directory, 'san_francisco.jpg'), 'wb') as out_file:shutil.copyfileobj(response.raw, out_file)del responseIn this example, we download an image from a URL and save it as san_francisco.jpg in the downloaded_images/ directory.
Check out PyTorch Resize Images
4. Using MatplotlibMatplotlib is a plotting library, but it can also be used to save images, especially when you’re working with plots and visualizations.
Example: Save a Plot as an ImageNow, let me show you an example of saving a plot as an image in Python using Matplotlib.
import matplotlib.pyplot as pltimport numpy as np# Generate some datadata = np.random.rand(10, 10)# Create a plotplt.imshow(data, cmap='hot', interpolation='nearest')# Save the plot as an imageplt.savefig('heatmap_seattle.png')Here, we generate a random heatmap and save it as heatmap_seattle.png. This is useful for saving visualizations and plots in Python.
Example: Save a Plot as an Image to a folderHere is an example of saving a plot as an image to a folder in Python.
import matplotlib.pyplot as pltimport numpy as npimport os# Generate some datadata = np.random.rand(10, 10)# Create a plotplt.imshow(data, cmap='hot', interpolation='nearest')# Define the directorydirectory = 'plots/'# Create directory if it doesn't existif not os.path.exists(directory):os.makedirs(directory)# Save the plot as an imageplt.savefig(os.path.join(directory, 'heatmap_seattle.png'))Here, we generate a random heatmap and save it as heatmap_seattle.png in the plots/ directory. This is particularly useful for saving visualizations and plots.
Check out Set Background to be an Image in Python Tkinter
5. Save Images with PickleFor more complex objects, such as custom image classes or additional metadata, you might want to use the pickle module to serialize and save your images.
Example: Save an Image with PickleHere is the complete Python code to save an image with Pickle.
import picklefrom PIL import Image# Open an imageimage = Image.open('chicago.jpg')# Save the image using picklewith open('chicago.pickle', 'wb') as f:pickle.dump(image, f)In this example, we serialize an image object and save it as chicago.pickle. This method is useful when saving more than just the raw image data.
Example: Create and Save Images to a DirectoryHere is another example of creating and saving images to a directory in Python.
import osfrom PIL import Image# Define the directorydirectory = 'project_images/'# Create directory if it doesn't existif not os.path.exists(directory):os.makedirs(directory)# Open an existing imageimage = Image.open('chicago.jpg')# Save the image to the directoryimage.save(os.path.join(directory, 'chicago_saved.jpg'))In this example, we create a directory named project_images/ and save an image as chicago_saved.jpg in that directory. The os.makedirs function ensures that the directory exists before saving the image.
ConclusionIn this tutorial, I explained how to save images in Python using various libraries like Pillow, OpenCV, Matplotlib, or even downloading images from the web. I also explained how to save images to a folder in Python.
You may also like:
How to attach an image in Turtle PythonBijay KumarI am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.
enjoysharepoint.com/