Skip to content

Instantly share code, notes, and snippets.

@almugabo
Last active May 31, 2021 08:43
Show Gist options
  • Save almugabo/f95b2e20a727c3b5bb7f6b0aa60e0ba5 to your computer and use it in GitHub Desktop.
Save almugabo/f95b2e20a727c3b5bb7f6b0aa60e0ba5 to your computer and use it in GitHub Desktop.
get picture from unsplash
# get photo from unsplash
# depends on python-unsplash
# !pip install python-unsplash
from unsplash.api import Api
from unsplash.auth import Auth
import requests
from PIL import Image
from io import BytesIO
def get_photo_unsplash(xpic_id,
xclient_id,
xclient_secret,
xpic_type = 'thumb',
xfull_response = False,
xsave_folder = None
):
'''
get photo from unsplash:
return :
- binary image
- credits line
type of picture can be
raw , full , regular, small or thumb
#usage
q1 = get_photo_unsplash(xpic_id = 'xxxx',
xclient_id = xxx['unsplash']['Access_Key'],
xclient_secret = xxxx['unsplash']['Secret_Key'] ,
xpic_type = 'thumb',
xsave_folder = '/home/xxxx/xx/xx/')
'''
#response in a dictionary
xdict_response = {}
#authenticate
x_auth = Auth(client_id = xclient_id,
client_secret = xclient_secret,
redirect_uri = '',
token=None,
code=None,
scope=None
)
x_api = Api(x_auth)
# get the picture,
#by error dct will be empty
try:
#get photo
xq1 = x_api.photo.get(xpic_id)
pic_url = eval('xq1.urls.' + xpic_type)
#get credit line
pic_username = xq1.user.username
xdict_response['pict_id'] = xpic_id
xdict_response['pict_url'] = pic_url
xdict_response['pict_credit'] = 'photo by {} on Unsplash. ({})'.format(pic_username, xpic_id)
# add full response if specified
if xfull_response:
xdict_response['pict_data'] = dict(xq1.__dict__)
#saving the image if folder specified
#get the image
except:
pass
if xsave_folder:
try:
image_filename = xsave_folder + xpic_id + '.png'
qq1 = requests.get(xdict_response['pict_url'])
img_binary = BytesIO(qq1.content)
img = Image.open(img_binary)
img.save(image_filename )
except:
print('error in saving:', xpic_id)
return xdict_response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment