Skip to content

Instantly share code, notes, and snippets.

@luismasuelli
Created January 18, 2021 02:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luismasuelli/ec0108f910c0c38dc01f3bee7820a4ab to your computer and use it in GitHub Desktop.
Save luismasuelli/ec0108f910c0c38dc01f3bee7820a4ab to your computer and use it in GitHub Desktop.
Get og:image and thumbnail it
from io import BytesIO
from PIL import Image
import requests
def get_image_from_body(soup):
"""
Given a soup, tries to get its og:image_tag.
:param soup: A parsed DOM, as a BeautifulSoup object.
:return: A PIL Image if everything went ok (a jpg/png image can be
retrieved via og:image meta tag's url), or None.
"""
image_tag = soup.select('meta[property="og:image"]')[0]
url = image_tag and image_tag.attrs['content']
if url:
response = requests.get(url)
if response.headers['content-type'] not in {'image/jpeg', 'image/x-png', 'image/png'}:
return None
else:
return Image.open(BytesIO(response.content))
return None
def get_thumbnail(image, size):
"""
A dummy method to clone the image, and convert it to thumbnail, preserving
the original image as well. Invoke (image).thumbnail((width, height)) if
you want to do an in-place thumbnailing of an image.
:param image: The image to make a thumbnail from.
:param size: The new size for the thumbnail.
:return: None, if the original image is None. Otherwise, a thumbnail, but
not in-place.
"""
if image is None:
return None
clone = image.copy()
clone.thumbnail(size)
return clone
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment