Skip to content

@janfabry /on-demand-resize.php
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
WordPress On-Demand image resizer plugin (first public attempt)
<?php
/*
Plugin Name: On-Demand image resizer
Plugin URI: http://www.monkeyman.be
Description: Create and store images in different sizes on demand
Version: 1.0
Author: Jan Fabry
This plugins monitors 404 requests to the uploads directory and created new images of a requested size. They are saved as new files in the upload directory, not cached somewhere, so future requests are served directly by the server. This allows you to eliminate the creation of intermediate image sizes [see monkeyman-virtual-intermediate-images] or resize images based on the size used in the editor [see monkeyman-resize-image-tags].
It uses the following format:
image.jpg -> base image
image-200x100.jpg -> resize exactly 200x100 (may distort aspect ratio!)
image-200.jpg -> resize to width 200, height in proportion (also 200x is accepted, to prevent confusion with "real" suffixes, like image-2.jpg)
image-x100.jpg -> resize to height 100, width in proportion
image-c200x100.jpg -> resize to smallest size that contains 200x100, crop in center
image-c200.jpg -> slice 200 wide in center, keep full height
image-cx100.jpg -> slice 100 height in center, keep full width
image-c200x100s15x25.jpg -> crop from (15,25) to (15+200,25+100), resulting in a 200x100 image
image-c300x150s15x25-200x100.jpg -> crop from (15,25) to (15+300,25+150), resize to 200x100
If you specify a size (the final 200x100, or if that is not there the crop size), the image will always have that size. This means that images can be distorted, and "upscaled" from smaller images. This is intentional, to keep the "API" simple.
This is almost like the standard WordPress convention, with the exception of cropped images. A 100x100 thumbnail would be named image-100x100.jpg by WordPress, but image-c100x100.jpg by us. Otherwise there would be no way to distinguish scale information from crop information when changing images (see [monkeyman-resize-img-tags].
The extension defines the output format, so image.png would convert the image to a PNG. There is one problem: future requests might use the PNG as the base image for resizes, instead of the real JPEG source. This should be solved by looking at the attachment data or timestamps.
There are two planned extensions: redirects and size names. A redirect would create a symlink if the image is identical to an existing image (if image.jpg is 300 by 400 pixels, image-300x400.jpg should just redirect there. Similar with crops: image-c200x200.jpg is identical to image-c100x100-200x200.jpg). As some hosts don't allow symlinks (FollowSymLinks on Apache?), we should create an image-300x400.jpg.redirect.txt or something like that to save these symlinks.
Size names would allow image-thumbnail.jpg to work. This is easy if you later redefine the thumbnail area (with a to-be-created plugin, solving [ http://wordpress.stackexchange.com/questions/1733/user-friendly-cropping-of-post-thumbnails ] - which explains why I added the crop start indicator). This should probably look at the attachment metadata.
Speaking of metadata, it might not be a bad idea to save our resized versions in the image metadata, so they get cleared when needed. But when is this needed? If you modify the image with the image editor, but I don't think this on-demand resizer combines well with the image editor. That's something to investigate further.
A big TODO is more input sanitation. We don't want this to be a backdoor to all files on our server. Also maybe some parameter validation, since there is no bounds checking for creating invalid images. And hooks. Lots of hooks.
If you think the variables have weird names ($idAttachment instead of $attachment_id), it's because I am trying to use "Apps Hungrarian" notation [ http://www.joelonsoftware.com/articles/Wrong.html ] to indicate the type of the value stored there. But I'm not consistent enough (and it clashes with WordPress coding standard), and maybe should rethink it.
Similar plugins and their image format strings:
picgrab: [(x0,y0,xs,ys)]<xd>x|x<yd>|<xd>x<yd>[c[<crop>]][;<cachetime>]
image.jpg&size=200x100
80x80 -> resize to fit in 80x80
200x50c -> resize to fill at least 200x50, crop center
50x200c -> resize to fill at least 50x200, crop center
100x100c0 -> resize to fill at least 100x100, crop left
100x100c50 -> resize to fill at least 100x100, crop center
100x100c100 -> resize to fill at least 100x100, crop right
simple-thumbs: w175|h75|c1|u1|fp
- width
- height
- crop: 0, 1
- unsharp: 0-3 (none - sharpest)
- format (png)
- resize mode (m): within, crop, portrait, landscape, auto
*/
class Monkeyman_OnDemandResizer
{
public function __construct()
{
add_action('template_redirect', array(&$this, 'checkUrl'));
}
public function checkUrl()
{
if (is_404()) {
$uploadInfo = wp_upload_dir();
$baseUploadInfo = parse_url($uploadInfo['baseurl']);
$baseUploadPath = $baseUploadInfo['path'];
$lenBaseUploadPath = strlen($baseUploadPath);
$requestPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
// Does our request begin with the upload path?
if (0 === strncmp($requestPath, $baseUploadPath, $lenBaseUploadPath)) {
$imagePath = substr($requestPath, $lenBaseUploadPath);
$this->checkImage($imagePath, $uploadInfo);
}
}
}
public function checkImage($imagePath, $uploadInfo)
{
if ($this->checkRedirect($imagePath, $uploadInfo)) {
exit();
}
/* TODO
// Safety check (funny business like '/../' in the request)
// Is the real path to our requested file still in the upload dir?
$rootedBaseUploadPath = $uploadInfo['basedir'];
$rootedImagePath = realpath($rootedBaseUploadPath . $imagePath);
$lenBaseRootedUploadPath = strlen($rootedBaseUploadPath);
var_dump($rootedBaseUploadPath . $imagePath, $rootedImagePath, $rootedBaseUploadPath, $lenBaseRootedUploadPath);
if (0 === strncmp($rootedImagePath, $rootedBaseUploadPath, $lenBaseRootedUploadPath)) {
*/
list($srcInfo, $dstInfo) = $this->parseRequest($imagePath, $uploadInfo);
/*
$origImageInfo = array(
'width' => null,
'height' => null,
'type' => null,
'fileName' => $resizedImageInfo['origImageFileName'],
'extension' => $resizedImageInfo['origImageExtension'],
'fullPath' => $resizedImageInfo['origImageFullPath'],
'attachmentId' => $resizedImageInfo['origAttachmentId'],
);
*/
$resSrcImage = wp_load_image($srcInfo['fullPath']);
if (!is_resource($resSrcImage)) {
var_dump('error_loading_image');
die();
}
$srcSize = @getimagesize($srcInfo['fullPath']);
if (!$srcSize) {
var_dump('invalid_image');
die();
}
$srcInfo['width'] = $srcSize[0];
$srcInfo['height'] = $srcSize[1];
$srcInfo['type'] = $srcSize[2];
$resizeInfo = $this->getResizeInfo($srcInfo, $dstInfo);
$resDstImage = wp_imagecreatetruecolor($resizeInfo['dstW'], $resizeInfo['dstH']);
imagecopyresampled(
$resDstImage,
$resSrcImage,
$resizeInfo['dstX'],
$resizeInfo['dstY'],
$resizeInfo['srcX'],
$resizeInfo['srcY'],
$resizeInfo['dstW'],
$resizeInfo['dstH'],
$resizeInfo['srcW'],
$resizeInfo['srcH']
);
if (IMAGETYPE_PNG == $dstInfo['type'] && function_exists('imageistruecolor') && !imageistruecolor($resSrcImage)) {
imagetruecolortopalette($resDstImage, false, imagecolorstotal($resSrcImage));
}
$imgwriters = array(
IMAGETYPE_GIF => 'imagegif',
IMAGETYPE_PNG => 'imagepng',
IMAGETYPE_JPEG => 'imagejpeg',
);
$imgwriter = $imgwriters[$dstInfo['type']];
imagedestroy($resSrcImage);
if (!isset($_REQUEST['tmp']) || !$_REQUEST['tmp']) {
// Write image to disk
$imgwriter($resDstImage, $dstInfo['fullPath']);
}
$mimetypes = array(
IMAGETYPE_GIF => 'image/gif',
IMAGETYPE_PNG => 'image/png',
IMAGETYPE_JPEG => 'image/jpeg',
);
status_header(200);
header('Content-Type: ' . $mimetypes[$dstInfo['type']]);
$imgwriter($resDstImage);
exit();
}
public function checkRedirect($imagePath, $uploadInfo)
{
// TODO
return false;
}
public function parseRequest($requestImagePath, $uploadInfo)
{
$srcInfo = array(
'filename' => null,
'extension' => null,
'type' => null,
'fullPath' => null,
'attachmentId' => null,
'doCrop' => false,
'cropWidth' => null,
'cropHeight' => null,
'cropStartX' => null,
'cropStartY' => null,
);
$dstInfo = array(
'filename' => null,
'extension' => null,
'type' => null,
'fullPath' => null,
'width' => null,
'height' => null,
'sizeName' => null,
);
$requestPathInfo = pathinfo($requestImagePath);
$requestFilename = $requestPathInfo['filename'];
$dstInfo['filename'] = $requestFilename;
$dstInfo['extension'] = strtolower($requestPathInfo['extension']);
$typeFromExtension = array(
'png' => IMAGETYPE_PNG,
'gif' => IMAGETYPE_GIF,
'jpg' => IMAGETYPE_JPEG,
'jpeg' => IMAGETYPE_JPEG,
);
$dstInfo['type'] = $typeFromExtension[$dstInfo['extension']];
$rootedUploadDir = $uploadInfo['basedir'] . $requestPathInfo['dirname'];
$dstInfo['fullPath'] = $rootedUploadDir . '/' . $dstInfo['filename'] . '.' . $dstInfo['extension'];
// Search for the original image
// Split the image name by '-', test for names starting with that
$requestFilenameParts = explode('-', $requestFilename);
$requestSizeParts = array();
$info['rootedDir'] = $rootedUploadDir;
$croppedFilename = $requestFilename;
$srcPathInfo = null;
while (is_null($srcPathInfo) && $croppedFilename) {
// TODO: Some escaping for this glob
$aGlobFiles = glob($rootedUploadDir . '/' . $croppedFilename . '*');
if ($aGlobFiles) {
foreach ($aGlobFiles as $srcPath) {
$srcPathInfo = pathinfo($srcPath);
if ($srcPathInfo['filename'] == $croppedFilename) {
// TODO: Is this really the source file? Compare attachment data or timestamps if multiple possible matches are found
$srcInfo['filename'] = $srcPathInfo['filename'];
$srcInfo['extension'] = $srcPathInfo['extension'];
$srcInfo['fullPath'] = $srcPath;
break 2;
}
$srcPathInfo = null;
}
}
$sizePart = array_pop($requestFilenameParts);
if ($sizePart) {
$requestSizeParts[] = $sizePart;
$croppedFilename = implode('-', $requestFilenameParts);
} else {
break;
}
}
// Search for a matching attachment ID
if ($srcInfo['filename']) {
global $wpdb;
$attachmentFileName = substr($requestPathInfo['dirname'], 1) . '/' .
$srcInfo['filename'] . '.' . $srcInfo['extension'];
$q = $wpdb->prepare('SELECT post_id FROM ' . $wpdb->postmeta . ' WHERE meta_value = \'%s\' AND meta_key = \'_wp_attached_file\'', $attachmentFileName);
$attachmentId = $wpdb->get_var($q);
if ($attachmentId) {
$srcInfo['attachmentId'] = intval($attachmentId);
}
}
// Parse the size params
// They can be size only, crop only, or size and crop
// Regex for:
// - 200, 200x
// - x400
// - 200x400
$sizeRegex = '((\d+)x?|x(\d+)|(\d+)x(\d+))';
// TODO: Parse size name ('large', 'medium', but also 'post-thumbnail' (with dashes!)
// Size string (200x400)
if (!empty($requestSizeParts) && preg_match('/^' . $sizeRegex . '$/', $requestSizeParts[0], $sizeMatches)) {
// 0: Full string
// 1: Full string
// 2: Width (only)
// 3: Height (only)
// 4: Width (if both)
// 5: Height (if both)
if ('' != $sizeMatches[2]) {
$dstInfo['width'] = intval($sizeMatches[2]);
}
if ('' != $sizeMatches[3]) {
$dstInfo['height'] = intval($sizeMatches[3]);
}
if ('' != $sizeMatches[4]) {
$dstInfo['width'] = intval($sizeMatches[4]);
}
if ('' != $sizeMatches[5]) {
$dstInfo['height'] = intval($sizeMatches[5]);
}
array_shift($requestSizeParts);
}
// Crop string
if (!empty($requestSizeParts) && preg_match('/^c' . $sizeRegex . '?(s' . $sizeRegex . ')?$/', $requestSizeParts[0], $cropMatches)) {
// 0: Full string
// 1: Crop size string (full, without 'c')
// 2: Crop width (only)
// 3: Crop height (only)
// 4: Crop width (if both)
// 5: Crop height (if both)
// 6: Crop start string (full, with 's')
// 7: Crop start string (full, without 's')
// 8: Crop start X (only)
// 9: Crop start Y (only)
// 10: Crop start X (if both)
// 11: Crop start Y (if both)
$srcInfo['doCrop'] = true;
if ('' != $cropMatches[2]) {
$srcInfo['cropWidth'] = intval($cropMatches[2]);
}
if ('' != $cropMatches[3]) {
$srcInfo['cropHeight'] = intval($cropMatches[3]);
}
if ('' != $cropMatches[4]) {
$srcInfo['cropWidth'] = intval($cropMatches[4]);
}
if ('' != $cropMatches[5]) {
$srcInfo['cropHeight'] = intval($cropMatches[5]);
}
if ('' != $cropMatches[8]) {
$srcInfo['cropStartX'] = intval($cropMatches[8]);
}
if ('' != $cropMatches[9]) {
$srcInfo['cropStartY'] = intval($cropMatches[9]);
}
if ('' != $cropMatches[10]) {
$srcInfo['cropStartX'] = intval($cropMatches[10]);
}
if ('' != $cropMatches[11]) {
$srcInfo['cropStartY'] = intval($cropMatches[11]);
}
}
return array(
$srcInfo,
$dstInfo,
);
}
/*
public function parseSizeName($sizeName, &$dstInfo, &$srcInfo)
{
$sizeInfo = false;
if ('thumb' == $sizeName) {
$sizeName = 'thumbnail';
}
$imageSizes = get_intermediate_image_sizes();
if (!in_array($sizeName, $imageSizes)) {
return false;
}
if (in_array($sizeName, array('thumbnail', 'medium', 'large'))) {
$sizeInfo = array(
'width' => intval(get_option($sizeName . '_size_w')),
'height' => intval(get_option($sizeName . '_size_h')),
);
} else {
global $_wp_additional_image_sizes;
if (array_key_exists($sizeName, $_wp_additional_image_sizes)) {
$sizeInfo = $_wp_additional_image_sizes[$sizeName];
}
}
return $sizeInfo;
}
*/
public function getResizeInfo($src, $dst)
{
$res = array(
'dstX' => 0,
'dstY' => 0,
);
// $o = $origImageInfo = $src;
// $r = $resizedImageInfo = $dst;
if (!$src['doCrop']) {
// Simple resize
$res['srcX'] = 0;
$res['srcY'] = 0;
$res['srcW'] = $src['width'];
$res['srcH'] = $src['height'];
// These can be overwritten later by the actual requested width and height
$res['dstW'] = $src['width'];
$res['dstH'] = $src['height'];
} else {
if (!$src['cropWidth'] && !$src['cropHeight']) {
var_dump('Crop needs at least width or height');
die();
}
$res['dstW'] = $src['cropWidth'];
$res['dstH'] = $src['cropHeight'];
if (!is_null($src['cropStartX']) && !is_null($src['cropStartY'])) {
// Simple crop, start location is given
$res['srcX'] = $src['cropStartX'];
$res['srcY'] = $src['cropStartY'];
$res['srcW'] = $src['cropWidth'];
$res['srcH'] = $src['cropHeight'];
} else {
if (!$src['cropWidth']) {
// No crop width
// Grab a horizontal slice $src['cropHeight'] high, all the way across
$res['srcX'] = 0;
$res['srcW'] = $src['width'];
$res['dstW'] = $src['width'];
$res['srcH'] = $src['cropHeight'];
$res['srcY'] = intval(($src['height'] - $res['srcH']) / 2);
} elseif (!$src['cropHeight']) {
// No crop height
// Grab a vertical slice $src['cropWidth'] wide, all the way across
$res['srcY'] = 0;
$res['srcH'] = $src['height'];
$res['dstH'] = $src['height'];
$res['srcW'] = $src['cropWidth'];
$res['srcX'] = intval(($src['width'] - $res['srcW']) / 2);
} else {
// Classic crop, find largest fitting area
$srcAspectRatio = $src['width'] / $src['height'];
$dstAspectRatio = $res['dstW'] / $res['dstH'];
if ($srcAspectRatio < $dstAspectRatio) {
// From left to right
$res['srcW'] = $src['width'];
$res['srcX'] = 0;
$res['srcH'] = intval($src['width'] / $dstAspectRatio);
$res['srcY'] = intval(($src['height'] - $res['srcH']) / 2);
} else {
// From top to bottom
$res['srcH'] = $src['height'];
$res['srcY'] = 0;
$res['srcW'] = intval($src['height'] * $dstAspectRatio);
$res['srcX'] = intval(($src['width'] - $res['srcW']) / 2);
}
}
}
}
// Rescale to given size
if ($dst['width'] && $dst['height']) {
$res['dstW'] = $dst['width'];
$res['dstH'] = $dst['height'];
} elseif ($dst['width']) {
// Width given, not height
// Calculate from aspect ratio
$res['dstH'] = intval($dst['width'] * ($res['dstH'] / $res['dstW']));
$res['dstW'] = $dst['width'];
} elseif ($dst['height']) {
// Height given, not width
// Calculate from aspect ratio
$res['dstW'] = intval($dst['height'] * ($res['dstW'] / $res['dstH']));
$res['dstH'] = $dst['height'];
}
return $res;
}
}
$monkeyman_OnDemandResizer_instance = new Monkeyman_OnDemandResizer();
@scribu

Isn't this dangerous? Suppose I find out you use this plugin on a certain site and I write a script that calls every combination of widths and heights in rapid succession. That could cause CPU spikes pretty easily, not to mention using up a lot of disk space.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.