Download an Image from a Url

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 and display an image from an URL in R?

If I try your code it looks like the image is downloaded. However, when opened with windows image viewer it also says it is corrupt.
The reason for this is that you don't have specified the mode in the download.file statement.

Try this:

download.file(y,'y.jpg', mode = 'wb')

For more info about the mode is see ?download.file

This way at least the file that you downloaded is working.

To view the image in R, have a look at

jj <- readJPEG("y.jpg",native=TRUE)
plot(0:1,0:1,type="n",ann=FALSE,axes=FALSE)
rasterImage(jj,0,0,1,1)

or how to read.jpeg in R 2.15
or Displaying images in R in version 3.1.0

Download Images from list of urls


  • Create a folder in your machine.

  • Place your text file of images URL in the folder.

  • cd to that folder.
  • Use wget -i images.txt

  • You will find all your downloaded files in the folder.

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')

Download Images from image url stored in array with javascript or best alternative

Using the download attribute of an anchor should do the trick...

EDIT

download only works for same-origin URLs, or the blob: and data: schemes. ref

Since this is not your case, you will have to create a blob with each image and fortunately, that is easy with the fetch API.

const downloadAll = async () => {
// Create and append a link
let link = document.createElement("a");
document.documentElement.append(link);

const imgArr = document.querySelectorAll("img");
for (let i = 0; i < imgArr.length; i++) {
await fetch(imgArr[i].src)
.then(res => res.blob()) // Gets the response and returns it as a blob
.then(blob => {

let objectURL = URL.createObjectURL(blob);

// Set the download name and href
link.setAttribute("download", `image_${i}.jpg`);
link.href = objectURL;

// Auto click the link
link.click();
})
}
};

Tested on CodePen.

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



Leave a reply



Submit