Resizing images in python with pillow
2020-Dec-02, Wednesday 07:48 pm![[personal profile]](https://www.dreamwidth.org/img/silk/identity/user.png)
Hello Internet. It's been a while, huh? Like many people, I got caught up in completely reconfiguring my workspace to accommodate a work-from-home station. Just yesterday I got to close all my IKEA tabs. It felt good. But unfortunately I haven't had the opportunity to get much work done on projects.
One of the short things I did manage was an update to my tweet-my-blog script, because my photos got too big so I needed to add handling to downsize before posting.
First, pull in a new library;
Then update the script (changes in strong);
One of the short things I did manage was an update to my tweet-my-blog script, because my photos got too big so I needed to add handling to downsize before posting.
First, pull in a new library;
pip3 install pillow
Then update the script (changes in strong);
#!/usr/bin/python3
from bs4 import BeautifulSoup
import feedparser
import os
from requests import get
import tweepy
import urllib3
from PIL import Image
consumer_key = 'your_key'
consumer_secret = 'your_secret'
access_token = 'your_access_token'
access_token_secret = 'your_access_token_secret'
# set up OAuth and integrate with API
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
# get RSS feed
blog = feedparser.parse('https://your_site_rss')
blog_title = 'Untitled'
# only really want most recent post
latest_blog = blog['entries'][0]
if 'title' in latest_blog:
blog_title = latest_blog['title']
tweet = "New blog post: \"" + blog_title + "\" - " + latest_blog['link']
img_link = ''
soup = BeautifulSoup(latest_blog['summary'], "lxml")
# get last img link (from main page, so not under cut)
if len(soup('p', attrs={'class':'image'})) > 0:
img_link = soup('p', attrs={'class':'image'})[-1].find('img')['src']
if len(img_link) > 0:
filename = 'temp.jpg'
with open(filename, 'wb') as image:
# download and save image
response = get(img_link)
image.write(response.content)
# scale image down to 25%
img = Image.open(filename)
width = int(round(img.size[0] / 4))
height = int(round(img.size[1] / 4))
small_img = img.resize((width, height), Image.ANTIALIAS)
thumbnailname = 'thumbnail.jpg'
small_img.save(thumbnailname)
print(tweet)
api.update_with_media(thumbnailname, status=tweet)
os.remove(filename)
os.remove(thumbnailname)
else:
print(tweet)
api.update_status(status=tweet)