Как сохранить фото в питоне
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images.
Image.save() Saves this image under the given filename. If no format is specified, the format to use is determined from the filename extension, if possible.
Keyword options can be used to provide additional instructions to the writer. If a writer doesn’t recognise an option, it is silently ignored. The available options are described in the image format documentation for each writer.
You can use a file object instead of a filename. In this case, you must always specify the format. The file object must implement the seek, tell, and write methods, and be opened in binary mode.
Syntax: Image.save(fp, format=None, **params)
Parameters:
fp – A filename (string), pathlib.Path object or file object.
format – Optional format override. If omitted, the format to use is determined from the filename extension. If a file object was used instead of a filename, this parameter should always be used.
options – Extra parameters to the image writer.
Returns: None
Raises:
KeyError – If the output format could not be determined from the file name. Use the format option to solve this.
IOError – If the file could not be written. The file may have been created, and may contain partial data.
Image Used:
How can I save an image with PIL?
I have just done some image processing using the Python image library (PIL) using a post I found earlier to perform fourier transforms of images and I can’t get the save function to work. The whole code works fine but it just wont save the resulting image:
The error I get is the following:
How can I save an image with Pythons PIL?
5 Answers 5
The error regarding the file extension has been handled, you either use BMP (without the dot) or pass the output name with the extension already. Now to handle the error you need to properly modify your data in the frequency domain to be saved as an integer image, PIL is telling you that it doesn’t accept float data to save as BMP.
Here is a suggestion (with other minor modifications, like using fftshift and numpy.array instead of numpy.asarray ) for doing the conversion for proper visualization:
![]()
You should be able to simply let PIL get the filetype from extension, i.e. use:
Try removing the . before the .bmp (it isn’t matching BMP as expected). As you can see from the error, the save_handler is upper-casing the format you provided and then looking for a match in SAVE . However the corresponding key in that object is BMP (instead of .BMP ).
I don’t know a great deal about PIL , but from some quick searching around it seems that it is a problem with the mode of the image. Changing the definition of j to:
Seemed to work for me (however note that I have very little knowledge of PIL , so I would suggest using @mmgp’s solution as s/he clearly knows what they are doing 🙂 ). For the types of mode , I used this page — hopefully one of the choices there will work for you.
Tutorial#
The most important class in the Python Imaging Library is the Image class, defined in the module with the same name. You can create instances of this class in several ways; either by loading images from files, processing other images, or creating images from scratch.
To load an image from a file, use the open() function in the Image module:
If successful, this function returns an Image object. You can now use instance attributes to examine the file contents:
The format attribute identifies the source of an image. If the image was not read from a file, it is set to None. The size attribute is a 2-tuple containing width and height (in pixels). The mode attribute defines the number and names of the bands in the image, and also the pixel type and depth. Common modes are “L” (luminance) for greyscale images, “RGB” for true color images, and “CMYK” for pre-press images.
If the file cannot be opened, an OSError exception is raised.
Once you have an instance of the Image class, you can use the methods defined by this class to process and manipulate the image. For example, let’s display the image we just loaded:
The standard version of show() is not very efficient, since it saves the image to a temporary file and calls a utility to display the image. If you don’t have an appropriate utility installed, it won’t even work. When it does work though, it is very handy for debugging and tests.
The following sections provide an overview of the different functions provided in this library.
Reading and writing images#
The Python Imaging Library supports a wide variety of image file formats. To read files from disk, use the open() function in the Image module. You don’t have to know the file format to open a file. The library automatically determines the format based on the contents of the file.
To save a file, use the save() method of the Image class. When saving files, the name becomes important. Unless you specify the format, the library uses the filename extension to discover which file storage format to use.
Convert files to JPEG#
A second argument can be supplied to the save() method which explicitly specifies a file format. If you use a non-standard extension, you must always specify the format this way:
Create JPEG thumbnails#
It is important to note that the library doesn’t decode or load the raster data unless it really has to. When you open a file, the file header is read to determine the file format and extract things like mode, size, and other properties required to decode the file, but the rest of the file is not processed until later.
This means that opening an image file is a fast operation, which is independent of the file size and compression type. Here’s a simple script to quickly identify a set of image files:
Identify Image Files#
Cutting, pasting, and merging images#
The Image class contains methods allowing you to manipulate regions within an image. To extract a sub-rectangle from an image, use the crop() method.
Copying a subrectangle from an image#
The region is defined by a 4-tuple, where coordinates are (left, upper, right, lower). The Python Imaging Library uses a coordinate system with (0, 0) in the upper left corner. Also note that coordinates refer to positions between the pixels, so the region in the above example is exactly 300×300 pixels.
The region could now be processed in a certain manner and pasted back.
Processing a subrectangle, and pasting it back#
When pasting regions back, the size of the region must match the given region exactly. In addition, the region cannot extend outside the image. However, the modes of the original image and the region do not need to match. If they don’t, the region is automatically converted before being pasted (see the section on Color transforms below for details).
Here’s an additional example:
Rolling an image#
Or if you would like to merge two images into a wider image:
Merging images#
For more advanced tricks, the paste method can also take a transparency mask as an optional argument. In this mask, the value 255 indicates that the pasted image is opaque in that position (that is, the pasted image should be used as is). The value 0 means that the pasted image is completely transparent. Values in-between indicate different levels of transparency. For example, pasting an RGBA image and also using it as the mask would paste the opaque portion of the image but not its transparent background.
The Python Imaging Library also allows you to work with the individual bands of an multi-band image, such as an RGB image. The split method creates a set of new images, each containing one band from the original multi-band image. The merge function takes a mode and a tuple of images, and combines them into a new image. The following sample swaps the three bands of an RGB image:
Splitting and merging bands#
Note that for a single-band image, split() returns the image itself. To work with individual color bands, you may want to convert the image to “RGB” first.
Geometrical transforms#
The PIL.Image.Image class contains methods to resize() and rotate() an image. The former takes a tuple giving the new size, the latter the angle in degrees counter-clockwise.
Simple geometry transforms#
To rotate the image in 90 degree steps, you can either use the rotate() method or the transpose() method. The latter can also be used to flip an image around its horizontal or vertical axis.
Transposing an image#
transpose(ROTATE) operations can also be performed identically with rotate() operations, provided the expand flag is true, to provide for the same changes to the image’s size.
A more general form of image transformations can be carried out via the transform() method.
Color transforms#
The Python Imaging Library allows you to convert images between different pixel representations using the convert() method.
Converting between modes#
The library supports transformations between each supported mode and the “L” and “RGB” modes. To convert between other modes, you may have to use an intermediate image (typically an “RGB” image).
Image enhancement#
The Python Imaging Library provides a number of methods and modules that can be used to enhance images.
Filters#
The ImageFilter module contains a number of pre-defined enhancement filters that can be used with the filter() method.
Applying filters#
Point Operations#
The point() method can be used to translate the pixel values of an image (e.g. image contrast manipulation). In most cases, a function object expecting one argument can be passed to this method. Each pixel is processed according to that function:
Applying point transforms#
Using the above technique, you can quickly apply any simple expression to an image. You can also combine the point() and paste() methods to selectively modify an image:
Processing individual bands#
Note the syntax used to create the mask:
Python only evaluates the portion of a logical expression as is necessary to determine the outcome, and returns the last value examined as the result of the expression. So if the expression above is false (0), Python does not look at the second operand, and thus returns 0. Otherwise, it returns 255.
Enhancement#
For more advanced image enhancement, you can use the classes in the ImageEnhance module. Once created from an image, an enhancement object can be used to quickly try out different settings.
You can adjust contrast, brightness, color balance and sharpness in this way.
Enhancing images#
Image sequences#
The Python Imaging Library contains some basic support for image sequences (also called animation formats). Supported sequence formats include FLI/FLC, GIF, and a few experimental formats. TIFF files can also contain more than one frame.
When you open a sequence file, PIL automatically loads the first frame in the sequence. You can use the seek and tell methods to move between different frames:
Reading sequences#
As seen in this example, you’ll get an EOFError exception when the sequence ends.
The following class lets you use the for-statement to loop over the sequence:
Using the ImageSequence Iterator class#
PostScript printing#
The Python Imaging Library includes functions to print images, text and graphics on PostScript printers. Here’s a simple example:
Drawing PostScript#
More on reading images#
As described earlier, the open() function of the Image module is used to open an image file. In most cases, you simply pass it the filename as an argument. Image.open() can be used as a context manager:
If everything goes well, the result is an PIL.Image.Image object. Otherwise, an OSError exception is raised.
You can use a file-like object instead of the filename. The object must implement file.read , file.seek and file.tell methods, and be opened in binary mode.
Reading from an open file#
To read an image from binary data, use the BytesIO class:
Reading from binary data#
Note that the library rewinds the file (using seek(0) ) before reading the image header. In addition, seek will also be used when the image data is read (by the load method). If the image file is embedded in a larger file, such as a tar file, you can use the ContainerIO or TarIO modules to access it.
Reading from URL#
Reading from a tar archive#
Batch processing#
Operations can be applied to multiple image files. For example, all PNG images in the current directory can be saved as JPEGs at reduced quality.
Since images can also be opened from a Path from the pathlib module, the example could be modified to use pathlib instead of the glob module.
Controlling the decoder#
Some decoders allow you to manipulate the image while reading it from a file. This can often be used to speed up decoding when creating thumbnails (when speed is usually more important than quality) and printing to a monochrome laser printer (when only a greyscale version of the image is needed).
The draft() method manipulates an opened but not yet loaded image so it as closely as possible matches the given mode and size. This is done by reconfiguring the image decoder.
Reading in draft mode#
This is only available for JPEG and MPO files.
This prints something like:
Note that the resulting image may not exactly match the requested mode and size. To make sure that the image is not larger than the given size, use the thumbnail method instead.
6 Ways to Save image to file in Python
In this Python tutorial, we will learn how to save an image to file in python.
Saving an image to a file in Python can be done using various methods. Here are some of the most common ways to save an image in Python:
- Using the OpenCV library
- Using the PIL library
- Using the URLLIB library
- Using the matplotlib library
- Using the pickle module
- Using the skimage library
Table of Contents
How to Python save an image to file
Let us see in detail the above 6 ways to save an image to a file in Python.
Method-1: Python save an image to file using OpenCV library
OpenCV is a popular computer vision library that provides a function cv2.imwrite() to save an image to a file in Python.
The above code uses the OpenCV and OS libraries in Python to perform the following tasks:
- Imports the required libraries: cv2 and os.
- Sets the file path for the source image to path, which is a string representing the file location on the local system.
- Sets the directory for saving the image to directory, which is a string representing the directory location on the local system.
- Loads the image using the cv2.imread() function and stores it in the variable img .
- Changes the current working directory to the specified directory for saving the image using the os.chdir() function.
- Prints the list of files in the directory before saving the image using the os.listdir() function and print() statement.
- Saves the image to the specified directory with the filename cat.jpg using the cv2.imwrite() function.
- Prints the list of files in the directory after saving the image using the os.listdir() function and print() statement.
Here, we can the list of directories before and after saving as the output. You can refer to the below screenshot for the output.

Method-2: Python save an image to file using the PIL library
PIL (Python Imaging Library) is another popular library for image manipulation in Python. It provides a method Image.save() to save an image to a file.
The above code uses the Python Imaging Library (PIL) to perform the following tasks:
- Imports the Image module from the PIL library using the from PIL import Image statement.
- Imports the PIL library using the import PIL statement.
- Opens an image with the specified file path using the Image.open() function and stores it in the picture variable.
- Saves the image with the specified filename dolls.jpg using the .save() method. The .save() method is a method of the Image class and is used to save the image to disk. The method updates the picture variable with the saved image.

Method-3: Python save an image to file using the matplotlib library
Matplotlib is a plotting library in Python that provides a function savefig() to save a figure to a file. To save an image, you can first plot it using Matplotlib and then save it using the savefig() function.
The above code uses the matplotlib library to perform the following tasks:
- Imports the Matplotlib’s Pyplot module using the import matplotlib.pyplot as plt statement.
- Reads the image file with the specified file path using the plt.imread() function and stores it in the img variable.
- Displays the image using the plt.imshow() function.
- Saves the image to disk with the specified file name saved_image.jpg using the plt.savefig() function.

Method-4: Python save an image to file using the URLLIB library
Another way to save an image to a file in Python is by using the urllib library. The urllib library provides a function urlretrieve() that can be used to download an image from a URL and save it to a file.
The above code uses the urllib and Python Imaging Library (PIL) to perform the following tasks:
- Imports the urllib and PIL libraries using the import urllib.request and from PIL import Image statements.
- Retrieves the image from the specified URL using the urllib.request.urlretrieve() function and stores the result in the new.png file.
- Opens the image with the specified file name new.png using the PIL.Image.open() function and stores it in the image variable.
- Displays the image using the image.show() function.
The URL is saved in the image format as the output in the below screenshot.

Method-5: Python save an image to file using the pickle module
The pickle module in Python can also be used to save an image to a file. Pickle is a module that allows you to serialize and deserialize Python objects, including images.
The above code performs the following tasks:
- Imports the pickle and matplotlib.pyplot modules.
- Reads an image file with the specified file path /content/saved_image.jpg using the plt.imread() function and stores the image data in the img variable.
- Opens a file with the specified name saved_image.pickle in write binary mode using the with open(“saved_image.pickle”, “wb”) as f: statement.
- Dumps the image data stored in the img variable into the opened file using the pickle.dump(img, f) statement. This process serializes the image data into binary form and writes it to the file, allowing it to be stored and retrieved later.

Method-6: Python save an image to file using the skimage library
Scikit-image is a library for image processing in Python that provides a function imsave() to save an image to a file.
The above code uses the skimage library to perform the following tasks:
- Imports the imsave and imread functions from the skimage.io module using the from skimage.io import imsave, imread statement.
- Reads the image file with the specified file path /content/simon-berger.jpg using the imread() function and stores it in the img variable.
- Saves the image to disk with the specified file name saved_image.jpg using the imsave() function. The img variable is passed as the image data to be saved.

You may also like to read the following Python tutorials.
In this tutorial, we have learned about how to save an image to file in python, and also we have covered these methods:
- Using the OpenCV library
- Using the PIL library
- Using the URLLIB
- Using the matplotlib library
- Using the pickle
- Using the skimage library

Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.