Skip to content

Instantly share code, notes, and snippets.

@cloverrose
Last active December 21, 2015 04:18
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 cloverrose/6248114 to your computer and use it in GitHub Desktop.
Save cloverrose/6248114 to your computer and use it in GitHub Desktop.
画像を正方形にトリミング・リサイズする。PIL(Pillow)を使っている。現在gifは上手く扱えない。 ImageMagick(Wand)を使った方はgifも適切に扱える。
# -*- coding:utf-8 -*-
"""
静的ファイルに関するユーティリティ群(PIL系 gifはうまく扱えない)
"""
import urllib
import contextlib
from PIL import Image
def download_image(url, filename):
"""
URLから画像データを取得
"""
try:
with contextlib.closing(urllib.urlopen(url)) as fin:
if 'image' not in fin.info().gettype():
return False
with open(filename, 'wb') as fout:
fout.write(fin.read())
return True
except Exception as e:
print e
return False
def square_image(input_filename, output_filename, size):
"""
画像ファイルを正方形にする
"""
img = Image.open(input_filename)
w, h = img.size
left, top, right, bottom = 0, 0, size, size
new_width, new_height = size, size
if w >= h: # 横幅が大きかったときの処理
new_width = size * w / h
left = (new_width - size) / 2
right = new_width - left
else: # 高さが大きかったときの処理
new_height = size * h / w
top = (new_height - size) / 2
bottom = new_height - top
img = img.resize((new_width, new_height), Image.ANTIALIAS)
img = img.crop((left, top, right, bottom))
img.save(output_filename, quality=100, optimize=True)
def download_and_square(url, original_name, square_name, size):
if download_image(url, original_name):
square_image(original_name, square_name, size)
# -*- coding:utf-8 -*-
"""
静的ファイルに関するユーティリティ群
"""
import urllib
import contextlib
from wand.image import Image
def download_image(url, filename):
"""
URLから画像データを取得
"""
try:
with contextlib.closing(urllib.urlopen(url)) as fin:
if 'image' not in fin.info().gettype():
return False
with open(filename, 'wb') as fout:
fout.write(fin.read())
return True
except Exception as e:
print e
return False
def square_image(input_filename, output_filename, size):
"""
画像ファイルを正方形にする
"""
img = Image(filename=input_filename)
w, h = img.size
left, top, right, bottom = 0, 0, size, size
new_width, new_height = size, size
if w >= h: # 横幅が大きかったときの処理
new_width = size * w / h
left = (new_width - size) / 2
right = new_width - left
else: # 高さが大きかったときの処理
new_height = size * h / w
top = (new_height - size) / 2
bottom = new_height - top
img.resize(width=new_width, height=new_height)
img.crop(left=left, top=top, right=right, bottom=bottom)
img.save(filename=output_filename)
def download_and_square(url, original_name, square_name, size):
if download_image(url, original_name):
square_image(original_name, square_name, size)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment