public
Last active

WordPress On-Demand image resizer plugin (first public attempt)

  • Download Gist
on-demand-resize.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
<?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();

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.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.