Как сохранить фото в питоне
Перейти к содержимому

Как сохранить фото в питоне

python save image from url

I got a problem when I am using python to save an image from url either by urllib2 request or urllib.urlretrieve. That is the url of the image is valid. I could download it manually using the explorer. However, when I use python to download the image, the file cannot be opened. I use Mac OS preview to view the image. Thank you!

The code is as follow

This URL is valid and I can save it through the browser but the python code would download a file that cannot be opened. The Preview says «It may be damaged or use a file format that Preview doesn’t recognize.» I compare the image that I download by Python and the one that I download manually through the browser. The size of the former one is several byte smaller. So it seems that the file is uncompleted, but I don’t know why python cannot completely download it.

Сохранение изображения с помощью cv2.imwrite() в OpenCV Python

Чтобы сохранить изображение в локальное хранилище с помощью Python, используйте функцию cv2.imwrite() в библиотеке OpenCV.

Синтаксис

Где, path – это полный путь к выходному файлу, в который вы хотите записать массив numpy изображений.

cv2.imwrite() возвращает логическое значение. true, если изображение успешно записано, и false, если изображение не было успешно записано по указанному локальному пути.

Пример 1

В этом примере мы прочитаем изображение, преобразуем его, а затем сохраним изображение в постоянном файловом хранилище с помощью метода imwrite().

Пример 2: со случайными значениями

В этом примере мы напишем массив numpy как изображение, используя функцию cv2.imwrite(). Для этого мы создадим массив с тремя каналами для красного, зеленого и синего, содержащий случайные значения. В общих случаях мы читаем изображение, применяем некоторые преобразования к массиву и затем записываем изображение в локальное хранилище. Но в этом примере мы будем придерживаться массива со случайными значениями.

Ниже приведено изображение, созданное со случайными значениями.

Пример функции imwrite()

В этом руководстве на примерах Python мы узнали, как использовать cv2.imwrite() для сохранения массива numpy в виде изображения.

Python save an image to file

In this Python tutorial, we will learn how to save an image to file in python and also we will cover these topics:

  • How to save an image in python
  • Python show image
  • Python save the image OpenCV2
  • Python save an image to file from URL
  • Read jpg from window clipboard in python
  • Convert string in base64 to image and save in file python
  • Python save the image file to a folder
  • Python write an image to file
  • Python save the image to file open cv

How to save an image using a pillow in python

Here, we can see how to save an image in python.

  • In this example, I have imported a module called Image from PIL and declared a variable picture, and assigned Image.open(r’Downloads\3.jpg’) the path and the name of the image along with extension.
  • And declared another variable and assigned picture.save(“dolls.jpg”) . Here, doll.jpg is the new name of the image.

In the below screenshot you can the image is saved as dolls.jpg.

How to save an image using a pillow in python

Python show image

Here, we can see how to show image in python.

  • In this example, I have imported a module called Image from PIL module and to open the image.
  • I have used image = Image.open(‘newpic.jpg’) to open the image. Image.open along with the name of the image and the extension.
  • The image.show() is used to show the image in python.

Python show image

Python save the file with OpenCV2

Here, we can see how to save the file with opencv2 in python.

  • In this example, I have imported a module called cv2 and os and taken a variable as a path and assigned a path and taken a directory as another variable, and assigned the path of the directory.
  • The imread is used to specify the way in which the image should be read, the os.chdir(directory) method to change current directories to a given path.
  • The image dora.jpg from the path is copied to the directory by changing the name dora.jpg to cat.jpg and listing the file name from the directory after save the cat.jpg file.
  • The os.listdir is used to list the directories, the directories will be listed before and after saving the image.

Here, we can the list of directories before and after saving as the output. You can refer to the below screenshot for the output:

Python save the file with OpenCV2

Python save an image to file from URL

Here, we can see how to save an image to file from URL in python.

  • In this example, I have imported a module called urllib.request. The urllib.request module defines functions and classes that help to open the URL.
  • I have imported the Image module from PIL, the urlretrieve method of the module used for retrieving the files, and the URL is assigned “https://bit.ly/3oAeohK”.
  • We can shorten the length of the URL by using URL Shortner tools.
  • The PIL.Image.open(“new.png”) is used to open the image, new.png is the name of the file.
  • The image.show() is used to display the image from the file.

The URL is saved in the image format as the output in the below screenshot.

Python save an image to file from URL

Read jpg from window clipboard in python

Here, we can see how to read jpg from window clipboard in python.

  • In this example, I have imported a module called win32clipboard. The .OpenClipboard() is used to open the clipboard and prevent other applications to modify the content.
  • When the application calls GetClipboardData() function the system performs implicit data format conversion between clipboard formats and copies the data.
  • To read the jpg file, I have opened the file as “savedImage.jpg” along with an extension, the ‘w’ mode is used to write the file and used f.write to write the content of the file.
  • The CloseClipboard() is used to close the clipboard so that other windows can access the clipboard.

Install Python Pyperclip module

To install this module we have to use

Below screenshot shows the output.

Read jpg from window clipboard in python

Convert string in base64 to image and save in file python

Here, we can how to convert string in base64 to image and save in file python.

  • In this example, I have imported a module called base64. The base64 is used to decode and encode also to convert the strings to byte format.
  • To open the file I have used with open(“book.png”, “wb”) as f , and to save and to write the file I have used print(f.write(base64.b64decode(‘book’))).
  • To decode the string to image base64.b64decode.

We can see the created file as the output. In the below screenshot.

Convert string in base64 to image and save in file python

Convert string in base64 to image and save in file python

Python save the image file to a folder

Here, we can see how to save image file to folder in python.

  • In this example, I have imported a module called cv2 and os and declared a variable as image and assigned image = cv2.imread(‘doll.jpg’). The doll.jpg is the name of the file.
  • The imread is used to load the image from the specified file, and the path of the folder is declared to save the image file to the folder.
  • To join the paths into a single path, I have used os.path.join.

In the below screenshot we can see that the image file is saved to the path that, we have specified.

Python save image file to folder

Python write an image to file

Now, we can see how to write an image to file in python

  • In this example, I have imported a module called Image from PIL and opened the dolls.jpg image file to read and the file which is read is read.
  • To write the image I have used opened the file named cartoon.png. To write the dolls.jpg image file into a new file called cartoon.png I have used file.write(). To close the file I have used file.close().

We can see that image is written to another file as the output. You can refer to the below screenshot for the output.

Python write an image to file

Python save the image to file open cv

Now, we can see how to save the image to file open cv in python

  • In this example I have imported module cv2 as cv and sys , and declared a variable as image and assigned cv.imread(cv.samples.findFile(“doll.jpg”)). The doll.jpg is the name of the file.
  • Here, I have taken if condition is none to check whether if an image is present or not. If the image is not present it returns “No image found.”
  • If the image is present it displays the image by using cv.imshow().
  • The ord() accepts the string as an argument and returns Unicode which is equal to the passed argument.
  • After returning the string(“s”) the imagefile is showed by using cv.imwrite(“doll.jpg”, image).

Below screenshot shows the image file as the output.

Python save the image to file open cv

You may like 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 topics:

  • How to save an image in python
  • Python show image
  • Python save the image OpenCV2
  • Python save an image to file from URL
  • Read jpg from window clipboard in python
  • Convert string in base64 to image and save in file python
  • Python save the image file to a folder
  • Python write an image to file
  • Python save the image to file open cv

Bijay Kumar MVP

Entrepreneur, Founder, Author, Blogger, Trainer, and more. Check out my profile.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *