python save image from url
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)
How to download an image to a specific local directory using either urllib or shutil?
I found a simpler solution. So I changed my code to use only Urllib. What I was missing was the forward slash at the end of the destination path which is C:users\user\Pictures\test/.
To add another piece of information as you can see in the code block urlretrieve uses the second argument as a location that you want to save.
import urllib.request
def download_jpg(url, file_path, file_name):
full_path = file_path + file_name + ".jpg"
urllib.request.urlretrieve(url, full_path)
url = input("Enter img URL to download: ")
file_name = input("Enter file name to save as: ")
download_jpg(url, r"C:\Users\User\Pictures\test/", file_name )
How do I download images with an https URL in Python 3?
May help you...
I made this script, but never finished (the final intention was make it running everyday automatically)
But to not be the kind of person who postpone the answers, here's the piece of code you're interest:
def downloadimg(self):
import datetime
imgurl = self.getdailyimg();
imgfilename = datetime.datetime.today().strftime('%Y%m%d') + '_' + imgurl.split('/')[-1]
with open(IMGFOLDER + imgfilename, 'wb') as f:
f.write(self.readimg(imgurl))
Hope it helps you out!
Edited
PS: using python3
Full script
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
IMGFOLDER = os.getcwd() + '/images/'
class BingImage(object):
"""docstring for BingImage"""
BINGURL = 'http://www.bing.com/'
JSONURL = 'HPImageArchive.aspx?format=js&idx=0&n=1&mkt=pt-BR'
LASTIMG = None
def __init__(self):
super(BingImage, self).__init__()
try:
self.downloadimg()
except:
pass
def getdailyimg(self):
import json
import urllib.request
with urllib.request.urlopen(self.BINGURL + self.JSONURL) as response:
rawjson = response.read().decode('utf-8')
parsedjson = json.loads(rawjson)
return self.BINGURL + parsedjson['images'][0]['url'][1:]
def downloadimg(self):
import datetime
imgurl = self.getdailyimg();
imgfilename = datetime.datetime.today().strftime('%Y%m%d') + '_' + imgurl.split('/')[-1]
with open(IMGFOLDER + imgfilename, 'wb') as f:
f.write(self.readimg(imgurl))
self.LASTIMG = IMGFOLDER + imgfilename
def checkfolder(self):
d = os.path.dirname(IMGFOLDER)
if not os.path.exists(d):
os.makedirs(d)
def readimg(self, url):
import urllib.request
with urllib.request.urlopen(url) as response:
return response.read()
def DefineBackground(src):
import platform
if platform.system() == 'Linux':
MAINCMD = "gsettings set org.gnome.desktop.background picture-uri"
os.system(MAINCMD + ' file://' + src)
def GetRandomImg():
"""Return a random image already downloaded from the images folder"""
import random
f = []
for (dirpath, dirnames, filenames) in os.walk(IMGFOLDER):
f.extend(filenames)
break
return IMGFOLDER + random.choice(f)
if __name__ == '__main__':
# get a new today's image from Bing
img = BingImage()
# check whether a new image was get or not
if(img.LASTIMG):
DefineBackground(img.LASTIMG)
else:
DefineBackground(GetRandomImg())
print('Background defined')
I downloaded image with urllib.request.urlretrieve and the image is downloaded but it does not open
It is not working because you are not pointing to an image. You are trying to download an html page as a png. Change the url to a png and it will work.
import urllib.request
def download_image(url):
full_name = "img3.png"
urllib.request.urlretrieve(url, full_name)
download_image("https://upload.wikimedia.org/wikipedia/commons/thumb/5/51/Google.png/800px-Google.png")
How to save an image locally using Python whose URL address I already know?
Python 2
Here is a more straightforward way if all you want to do is save it as a file:
import urllib
urllib.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg")
The second argument is the local path where the file should be saved.
Python 3
As SergO suggested the code below should work with Python 3.
import urllib.request
urllib.request.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg")
Related Topics
Dynamically Evaluate an Expression from a Formula in Pandas
Regular Expression to Return Text Between Parenthesis
Copying Nested Lists in Python
Animated Sprite from Few Images
Is There a Simple Way to Delete a List Element by Value
Tensorflow Not Found Using Pip
Import Error: No Module Name Urllib2
Moving Average or Running Mean
Live Output from Subprocess Command
What Should I Do with "Unexpected Indent" in Python
Why Can't I Use a List as a Dict Key in Python
How to Print the Value of a Tensor Object in Tensorflow
Creating a Dictionary from a CSV File
Understanding the Map Function