Python image open by url

Reading image from URL in Python

Learn how to read an image from URL in Python with this tutorial.

Many times a situation may arrive where you need to download images instantly from the internet, and not only one image there are a bunch of images, In this doing manual copy and pasting can be Boring and time-consuming task to do, You need a reliable and faster solution to this task.

So, In this tutorial, we will be learning how to read and download images using ‘URL’ in Python. Here we will be using Firstly, the ‘sys’ module so that we can give input URL directly on the command line while running our program. Second, we will be using the ‘Pillow’ library for opening an image as an object and lastly, the most important one is the ‘Requests’ Library of Python for opening and downloading the image from a specified URL.

About Requests Library

Requests library is used for processing HTTP requests in python. This library allows request methods like get, put, post, delete, etc. Some of the features that are supported by the library are:

  • Automatic URL formation consisting of post data using ‘urllib3’.
  • International Domains and URLs can be accessed.
  • SSL Certificate verification.
  • Both Basic and Digest Authentication.
  • Unicode Response bodies.
  • Returns cookies in as Dictionary.
Читайте также:  Python open stdout as file

To learn More about Requests Library you read its detailed documentation.

How to read an image from URL in Python

Before we start with the actual code first we need to install required libraries or modules.

Installation:

$ pip3 install pillow $ pip3 install requests

After installation, we can start with the code. I would suggest you first get through the code then I’ll be explaining to you the important things.

Source Code:

# Importing Required Modules import sys import requests from PIL import Image # Exception Handling for invalid requests try: # Creating an request object to store the response # The URL is refrenced sys.argv[1] ImgRequest = requests.get(sys.argv[1]) # Verifying whether the specified URL exist or not if ImgRequest.status_code == requests.codes.ok: # Opening a file to write bytes from response content # Storing this onject as an image file on the hard drive img = open("test.jpg","wb") img.write(ImgRequest.content) img.close() # Opening Inage file using PIL Image img = Image.open("test.jpg") img.show() else: print(ImgRequest.status_code) except Exception as e: print(str(e))

Now here we will be supplying the image URL as command line argument which would we referenced later by the sys.argv object. After the request has been made the response status code is verified whether it is in the codes range (>200 & <=400). Once the status code is verified then the response content would be written into a binary file and saved as an image file. Later we open it using Pil Module for taking a view.

Input:

$ python3 request.py https://www.fujifilm.co.nz/products/digital_cameras/x/fujifilm_x_t1/sample_images/img/index/ff_x_t1_001.JPG

Here ‘request.py’ is the python source file.

Output:

How to read image from URL in Python

So In this way, you can read an image from URL using Python. I hope this tutorial was fruitful to you, Thank you ‘Keep Learning Keep Coding’.

Источник

Reading image from URL in Python

Learn how to read an image from URL in Python with this tutorial.

Many times a situation may arrive where you need to download images instantly from the internet, and not only one image there are a bunch of images, In this doing manual copy and pasting can be Boring and time-consuming task to do, You need a reliable and faster solution to this task.

So, In this tutorial, we will be learning how to read and download images using ‘URL’ in Python. Here we will be using Firstly, the ‘sys’ module so that we can give input URL directly on the command line while running our program. Second, we will be using the ‘Pillow’ library for opening an image as an object and lastly, the most important one is the ‘Requests’ Library of Python for opening and downloading the image from a specified URL.

About Requests Library

Requests library is used for processing HTTP requests in python. This library allows request methods like get, put, post, delete, etc. Some of the features that are supported by the library are:

  • Automatic URL formation consisting of post data using ‘urllib3’.
  • International Domains and URLs can be accessed.
  • SSL Certificate verification.
  • Both Basic and Digest Authentication.
  • Unicode Response bodies.
  • Returns cookies in as Dictionary.

To learn More about Requests Library you read its detailed documentation.

How to read an image from URL in Python

Before we start with the actual code first we need to install required libraries or modules.

Installation:

$ pip3 install pillow $ pip3 install requests

After installation, we can start with the code. I would suggest you first get through the code then I’ll be explaining to you the important things.

Source Code:

# Importing Required Modules import sys import requests from PIL import Image # Exception Handling for invalid requests try: # Creating an request object to store the response # The URL is refrenced sys.argv[1] ImgRequest = requests.get(sys.argv[1]) # Verifying whether the specified URL exist or not if ImgRequest.status_code == requests.codes.ok: # Opening a file to write bytes from response content # Storing this onject as an image file on the hard drive img = open("test.jpg","wb") img.write(ImgRequest.content) img.close() # Opening Inage file using PIL Image img = Image.open("test.jpg") img.show() else: print(ImgRequest.status_code) except Exception as e: print(str(e))

Now here we will be supplying the image URL as command line argument which would we referenced later by the sys.argv object. After the request has been made the response status code is verified whether it is in the codes range (>200 & <=400). Once the status code is verified then the response content would be written into a binary file and saved as an image file. Later we open it using Pil Module for taking a view.

Input:

$ python3 request.py https://www.fujifilm.co.nz/products/digital_cameras/x/fujifilm_x_t1/sample_images/img/index/ff_x_t1_001.JPG

Here ‘request.py’ is the python source file.

Output:

How to read image from URL in Python

So In this way, you can read an image from URL using Python. I hope this tutorial was fruitful to you, Thank you ‘Keep Learning Keep Coding’.

Источник

Четыре метода загрузки изображений с веб-сайта с помощью Python

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

1-ый метод

Первый метод использует модуль urllib (или же urllib2). Пусть имеется ссылка на некое изображение img. Метод выглядит следующим образом:

import urllib resource = urllib.urlopen(img) out = open(". \img.jpg", 'wb') out.write(resource.read()) out.close() 

Здесь нужно обратить внимание, что режим записи для изображений — ‘wb’ (бинарный), а не просто ‘w’.

2-ой метод

Второй метод использует тот же самый urllib. В дальнейшем будет показано, что этот метод чуть медленнее первого (отрицательный оттенок фактора скорости парсинга неоднозначен), но достоин внимания из-за своей краткости:

import urllib urllib.urlretrieve(img, ". \img.jpg") 

Притом стоит заметить, что функция urlretrieve в библиотеке urllib2 по неизвестным мне причинам (может кто подскажет по каким) отсутствует.

3-ий метод

Третий метод использует модуль requests. Метод имеет одинаковый порядок скорости выгрузки картинок с первыми двумя методами:

import requests p = requests.get(img) out = open(". \img.jpg", "wb") out.write(p.content) out.close() 

При этом при работе с веб в питоне рекомендуется использовать именно requests вместо семейств urllib и httplib из-за его краткости и удобства обращения с ним.

4-ый метод

Четвертый метод по скорости кардинально отличается от предыдущих методов (на целый порядок). Основан на использовании модуля httplib2. Выглядит следующим образом:

import httplib2 h = httplib2.Http('.cache') response, content = h.request(img) out = open('. \img.jpg', 'wb') out.write(content) out.close() 

Здесь явно используется кэширование. Без кэширования (h = httplib2.Http()) метод работает в 6-9 раза медленнее предыдущих аналогов.

Тестирование скорости проводилось на примере скачивания картинок с расширением *.jpg c сайта новостной ленты lenta.ru. Выбор картинок, подпадающих под этот критерий и измерение времени выполнения программы производились следующим образом:

import re, time, urllib2 url = "http://lenta.ru/" content = urllib2.urlopen(url).read() imgUrls = re.findall('img .*?src="https://habr.com/ru/articles/210238/(.*?)"', сontent) start = time.time() for img in imgUrls: if img.endswith(".jpg"): """реализация метода по загрузке изображения из url""" print time.time()-start 

Постоянно меняющиеся картинки на сайте не повлияли на чистоту измерений, поскольку методы отрабатывали друг за другом. Полученные результаты таковы:

Таблица сравнения скоростей методов

Метод 1, с Метод 2, с Метод 3, с Метод 4, с (без кэширования, с)
0.823 0.908 0.874 0.089 (7.625)

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

Источник

Четыре метода загрузки изображений с веб-сайта с помощью Python

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

1-ый метод

Первый метод использует модуль urllib (или же urllib2). Пусть имеется ссылка на некое изображение img. Метод выглядит следующим образом:

import urllib resource = urllib.urlopen(img) out = open(". \img.jpg", 'wb') out.write(resource.read()) out.close() 

Здесь нужно обратить внимание, что режим записи для изображений — ‘wb’ (бинарный), а не просто ‘w’.

2-ой метод

Второй метод использует тот же самый urllib. В дальнейшем будет показано, что этот метод чуть медленнее первого (отрицательный оттенок фактора скорости парсинга неоднозначен), но достоин внимания из-за своей краткости:

import urllib urllib.urlretrieve(img, ". \img.jpg") 

Притом стоит заметить, что функция urlretrieve в библиотеке urllib2 по неизвестным мне причинам (может кто подскажет по каким) отсутствует.

3-ий метод

Третий метод использует модуль requests. Метод имеет одинаковый порядок скорости выгрузки картинок с первыми двумя методами:

import requests p = requests.get(img) out = open(". \img.jpg", "wb") out.write(p.content) out.close() 

При этом при работе с веб в питоне рекомендуется использовать именно requests вместо семейств urllib и httplib из-за его краткости и удобства обращения с ним.

4-ый метод

Четвертый метод по скорости кардинально отличается от предыдущих методов (на целый порядок). Основан на использовании модуля httplib2. Выглядит следующим образом:

import httplib2 h = httplib2.Http('.cache') response, content = h.request(img) out = open('. \img.jpg', 'wb') out.write(content) out.close() 

Здесь явно используется кэширование. Без кэширования (h = httplib2.Http()) метод работает в 6-9 раза медленнее предыдущих аналогов.

Тестирование скорости проводилось на примере скачивания картинок с расширением *.jpg c сайта новостной ленты lenta.ru. Выбор картинок, подпадающих под этот критерий и измерение времени выполнения программы производились следующим образом:

import re, time, urllib2 url = "http://lenta.ru/" content = urllib2.urlopen(url).read() imgUrls = re.findall('img .*?src="https://habr.com/ru/articles/210238/(.*?)"', сontent) start = time.time() for img in imgUrls: if img.endswith(".jpg"): """реализация метода по загрузке изображения из url""" print time.time()-start 

Постоянно меняющиеся картинки на сайте не повлияли на чистоту измерений, поскольку методы отрабатывали друг за другом. Полученные результаты таковы:

Таблица сравнения скоростей методов

Метод 1, с Метод 2, с Метод 3, с Метод 4, с (без кэширования, с)
0.823 0.908 0.874 0.089 (7.625)

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

Источник

Оцените статью