python save image from url

177,002

Solution 1

A sample code that works for me on Windows:

import requests

with open('pic1.jpg', 'wb') as handle:
    response = requests.get(pic_url, stream=True)

    if not response.ok:
        print(response)

    for block in response.iter_content(1024):
        if not block:
            break

        handle.write(block)

Solution 2

import requests

img_data = requests.get(image_url).content
with open('image_name.jpg', 'wb') as handler:
    handler.write(img_data)

Solution 3

It is the simplest way to download and save the image from internet using urlib.request package.

Here, you can simply pass the image URL(from where you want to download and save the image) and directory(where you want to save the download image locally, and give the image name with .jpg or .png) Here I given "local-filename.jpg" replace with this.

Python 3

import urllib.request
imgURL = "http://site.meishij.net/r/58/25/3568808/a3568808_142682562777944.jpg"

urllib.request.urlretrieve(imgURL, "D:/abc/image/local-filename.jpg")

You can download multiple images as well if you have all the image URLs from the internet. Just pass those image URLs in for loop, and the code automatically download the images from the internet.

Solution 4

Python code snippet to download a file from an url and save with its name

import requests

url = 'http://google.com/favicon.ico'
filename = url.split('/')[-1]
r = requests.get(url, allow_redirects=True)
open(filename, 'wb').write(r.content)

Solution 5

import random
import urllib.request

def download_image(url):
    name = random.randrange(1,100)
    fullname = str(name)+".jpg"
    urllib.request.urlretrieve(url,fullname)     
download_image("http://site.meishij.net/r/58/25/3568808/a3568808_142682562777944.jpg")
Share:
177,002
Shaoxiang Su
Author by

Shaoxiang Su

Updated on July 05, 2022

Comments

  • Shaoxiang Su
    Shaoxiang Su almost 2 years

    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!

    UPDATE:

    The code is as follow

    def downloadImage(self):
        request = urllib2.Request(self.url)
        pic = urllib2.urlopen(request)
        print "downloading: " + self.url
        print self.fileName
        filePath = localSaveRoot + self.catalog  + self.fileName + Picture.postfix
        # urllib.urlretrieve(self.url, filePath)
        with open(filePath, 'wb') as localFile:
            localFile.write(pic.read())
    

    The image URL that I want to download is http://site.meishij.net/r/58/25/3568808/a3568808_142682562777944.jpg

    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.

  • Shaoxiang Su
    Shaoxiang Su about 9 years
    That's perfect! Thank you so much! I don't know why requests module could complete that while urllib and urllib2 cannot do that, but anyways.
  • Mona Jalal
    Mona Jalal about 6 years
    @vlad what if we are not aware of the image extension from the URL but we know it is an image?
  • Vlad Bezden
    Vlad Bezden about 6 years
    @MonaJalal you don't have to specify an extension, as long as you have valid qualified URL address.
  • Max Vollmer
    Max Vollmer over 5 years
    Welcome to Stackoverflow and thanks for your contribution! Could you add an explanation to your answer what the code does and why it works? Thanks!
  • Eswar
    Eswar about 5 years
    How do I add the headers for url in urlretrieve? I had a problem with images opening in the browser but not through code using urlretrive. I have tried urlopen but I don't know how to download the image using urlopen.
  • devugur
    devugur over 3 years
    pip install requests if you don't have
  • Felipe Toledo
    Felipe Toledo almost 3 years
    Using '.content' after requests.get() is the key to save an image
  • Cleb
    Cleb over 2 years
    That gives me an empty image for the following URL: genome.jp/pathway/ko02024+K07173 Any idea how to fix this?
  • Cleb
    Cleb over 2 years
    It does not work for the following URL; any idea how to fix it? genome.jp/pathway/ko02024+K07173
  • Cleb
    Cleb over 2 years
    It does not work for the following URL; any idea how to fix it? genome.jp/pathway/ko02024+K07173
  • Shidouuu
    Shidouuu over 2 years
    @Cleb That's not an image
  • RAZ0229
    RAZ0229 over 2 years
    @Cleb That's because the url you provided doesn't belong to an image. Try it with url1 = 'https://www.genome.jp/tmp/mark_pathway1641220140108369/ko02‌​024.png' in this case
  • Parseval
    Parseval about 2 years
    @VladBezden - This saves the image to a folder, but when I open the image it says that windows does not support the file format, despite it being a simple jpg. Do you know why?
  • Parseval
    Parseval about 2 years
    This saves the image to a folder, but when I open the image it says that windows does not support the file format, despite it being a simple jpg. Anyone who knows why?
  • Parseval
    Parseval about 2 years
    I tried this but I get an error: HTTPError: Forbidden. Do you know why this is? I'm using this URL: assets.ellosgroup.com/i/ellos/ell_1682670-01_Fs.