Created
August 11, 2010 14:28
-
-
Save roosmaa/519056 to your computer and use it in GitHub Desktop.
Resizes a picture to fit in a box, clipping the edges if necessary. When picture smaller than the given box, centers the picture and adds a transparent background.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php function boxed_thumbnail($data, $size) | |
{ | |
$src = imagecreatefromstring($data); | |
$src_width = imagesx($src); | |
$src_height = imagesy($src); | |
// Resize algo: | |
$src_ratio = $src_width / $src_height; | |
$trg_ratio = $size[0] / $size[1]; | |
// Fall back values: | |
$dst_width = $src_width; | |
$dst_height = $src_height; | |
if ($src_ratio >= $trg_ratio) | |
{ | |
if ($src_height > $size[1]) | |
{ | |
$dst_width = $size[1] * $src_ratio; | |
$dst_height = $size[1]; | |
} | |
} | |
else | |
{ | |
if ($src_width > $size[0]) | |
{ | |
$dst_width = $size[0]; | |
$dst_height = $size[0] / $src_ratio; | |
} | |
} | |
$dst = imagecreatetruecolor($size[0], $size[1]); | |
$bg_color = imagecolorallocatealpha($dst, 255, 255, 255, 127); | |
imagefill($dst, 0, 0, $bg_color); | |
imagecopyresampled( | |
$dst, | |
$src, | |
($size[0] - $dst_width) / 2, // dst_x | |
($size[1] - $dst_height) / 2, // dst_y | |
0, // src_x | |
0, // src_y | |
$dst_width, | |
$dst_height, | |
$src_width, | |
$src_height | |
); | |
ob_start(); | |
imagepng($dst); | |
$data = ob_get_clean(); | |
imagedestroy($src); | |
imagedestroy($dst); | |
return $data; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from PIL import Image | |
from StringIO import StringIO | |
def boxed_thumbnail(data, size): | |
src = Image.open(data) | |
src_width = src.size[0] | |
src_height = src.size[1] | |
# Resize algo: | |
src_ratio = float(src_width) / src_height | |
trg_ratio = float(size[0]) / size[1] | |
# Fall back values: | |
dst_width = src_width; | |
dst_height = src_height; | |
if src_ratio >= trg_ratio: | |
if src_height > size[1]: | |
dst_width = int(size[1] * src_ratio) | |
dst_height = size[1] | |
else: | |
if src_width > size[0]: | |
dst_width = size[0]; | |
dst_height = int(size[0] / src_ratio) | |
dst = Image.new('RGBA', size, (255, 255, 255, 0)) | |
dst.paste( | |
src.resize((dst_width, dst_height)), | |
( | |
(size[0] - dst_width) / 2, | |
(size[1] - dst_height) / 2, | |
) | |
) | |
buf = StringIO() | |
dst.save(buf, format='PNG') | |
buf.seek(0) | |
return buf |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment