diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..fb5b2b4 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,55 @@ +# License + +## StackBlur + +Gaussholder uses [StackBlur for Canvas][stackblur] by Mario Klingemann; modified +by [Fabien Loison][stackblur-gh]. Licensed under the MIT License. + +[stackblur]: http://www.quasimondo.com/StackBlurForCanvas/StackBlurDemo.html +[stackblur-gh]: https://github.com/flozz/StackBlur + +> Copyright (c) 2010 Mario Klingemann +> +> Permission is hereby granted, free of charge, to any person +> obtaining a copy of this software and associated documentation +> files (the "Software"), to deal in the Software without +> restriction, including without limitation the rights to use, +> copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the +> Software is furnished to do so, subject to the following +> conditions: +> +> The above copyright notice and this permission notice shall be +> included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +> OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +> NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +> HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +> WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +> FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +> OTHER DEALINGS IN THE SOFTWARE. + +## Gaussholder + +Gaussholder is a plugin for (and hence, derivative work of) WordPress. Licensed +under the GNU General Public License version 2 or later. + +> WordPress - Web publishing software +> +> Copyright (C) 2003-2010 by the contributors +> +> This program is free software; you can redistribute it and/or modify +> it under the terms of the GNU General Public License as published by +> the Free Software Foundation; either version 2 of the License, or +> (at your option) any later version. +> +> This program is distributed in the hope that it will be useful, +> but WITHOUT ANY WARRANTY; without even the implied warranty of +> MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +> GNU General Public License for more details. +> +> You should have received a copy of the GNU General Public License along +> with this program; if not, write to the Free Software Foundation, Inc., +> 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. diff --git a/README.md b/README.md new file mode 100644 index 0000000..d1c42cc --- /dev/null +++ b/README.md @@ -0,0 +1,97 @@ + + + + + + + + + +
+ Gaussholder
+ Fast and lightweight image previews, using Gaussian blur. +
+ +
+ A Human Made project. Maintained by @rmccue. + + +
+ +Gaussholder is an image placeholder utility, generating accurate preview images using an amazingly small amount of data. + + + +That's a **800 byte** preview image, for a **109 kilobyte** image. 800 bytes still too big? Tune the size to your liking in your configuration. + +**Please note:** This is still in development, and we're working on getting this production-ready, so things might not be settled yet. In particular, we're still working on tweaking the placeholder size and improving the lazyloading code. Avoid using this in production. + +## How does it work? + +Gaussholder is inspired by [Facebook Engineering's fantastic post][fbeng] on generating tiny preview images. Gaussholder takes the concepts from this post and applies them to the wild world of WordPress. + +In a nutshell, Gaussholder takes a Gaussian blur and applies it to an image to generate a preview image. Gaussian blurs work as a low-pass filter, allowing us to throw away a lot of the data. We then further reduce the amount of data per image by removing the JPEG header and rebuilding it on the client side (this eliminates ~800 bytes from each image). + +We further reduce the amount of data for some requests by lazyloading images. + +[fbeng]: https://code.facebook.com/posts/991252547593574 + +## How do I use it? + +Gaussholder is designed for high-volume sites for seriously advanced users. Do _not_ install this on your regular WP site. + +1. Download and activate the plugin from this repo. +2. Select the image sizes to use Gaussholder on, and add them to the array on the `gaussholder.image_sizes` filter. +3. If you have existing images, regenerate the image thumbnails. + +Your filter should look something like this: + +```php +add_filter( 'gaussholder.image_sizes', function ( $sizes ) { + $sizes['medium'] = 16; + $sizes['large'] = 32; + $sizes['full'] = 84; + return $sizes; +} ); +``` + +The keys are registered image sizes (plus `full` for the original size), with the value as the desired blur radius in pixels. + +By default, Gaussholder won't generate any placeholders, and you need to opt-in to using it. Simply filter here, and add the size names for what you want generated. + +Be aware that for every size you add, a placeholder will be generated and stored in the database. If you have a lot of sizes, this will be a _lot_ of data. + +### Blur radius + +The blur radius controls how much blur we use. The image is pre-scaled down by this factor, and this is really the key to how the placeholders work. Increasing radius decreases the required data quadratically: a radius of 2 uses a quarter as much data as the full image; a radius of 8 uses 1/64 the amount of data. (Due to compression, the final result will *not* follow this scaling.) + +Be careful tuning this, as decreasing the radius too much will cause a huge amount of data in the body; increasing it will end up with not enough data to be an effective placeholder. + +The radius needs to be tuned to each size individually. Facebook uses about 200 bytes of data for their placeholders, but you may want higher quality placeholders. There's no ideal radius, as you simply want to balance having a useful placeholder with the extra time needed to process the data on the page. + +Gaussholder includes a CLI command to help you tune the radius: pick a representative attachment or image file and use `wp gaussholder check-size `. Adjust the radius until you get to roughly 200B, then check against other attachments to ensure they're in the ballpark. + +Note: changing the radius requires regenerating the placeholder data. Run `wp gaussholder process-all --regenerate` after changing radii or adding new sizes. + +## License +Gaussholder is licensed under the GPLv2 or later. + +Gaussholder uses StackBlur, licensed under the MIT license. + +See [LICENSE.md](LICENSE.md) for further details. + +## Credits +Created by Human Made for high volume and large-scale sites. + +Written and maintained by [Ryan McCue](https://github.com/rmccue). Thanks to all our [contributors](https://github.com/humanmade/Gaussholder/graphs/contributors). (Thanks also to fellow humans Matt and Paul for the initial placeholder code.) + +Gaussholder is heavily inspired by [Facebook Engineering's post][fbeng], and would not have been possible without it. In particular, the techniques of downscaling before blurring and extracting the JPEG header are particularly novel, and the key to why Gaussholder exists. + +Interested in joining in on the fun? [Join us, and become human!](https://hmn.md/is/hiring/) diff --git a/assets/blank.gif b/assets/blank.gif new file mode 100644 index 0000000..f191b28 Binary files /dev/null and b/assets/blank.gif differ diff --git a/assets/gaussholder.js b/assets/gaussholder.js new file mode 100644 index 0000000..3cad36c --- /dev/null +++ b/assets/gaussholder.js @@ -0,0 +1,231 @@ +window.Gaussholder = (function (header) { + // Fade duration in ms when the image loads in. + var fadeDuration = 800; + + var arrayBufferToBase64 = function( buffer ) { + var binary = ''; + var bytes = new Uint8Array( buffer ); + var len = bytes.byteLength; + for (var i = 0; i < len; i++) { + binary += String.fromCharCode( bytes[ i ] ); + } + return window.btoa( binary ); + }; + + var reconstituteImage = function (header, image) { + var image_data = image[0], + width = parseInt( image[1] ), + height = parseInt( image[2] ); + + var full = atob( header.header ) + atob( image_data ); + var bytes = new Uint8Array( full.length ); + for (var i = 0; i < full.length; i++) { + bytes[i] = full.charCodeAt(i); + } + + // Poke the bits. + bytes[ header.height_offset ] = ( (height >> 8) & 0xFF); + bytes[ header.height_offset + 1 ] = (height & 0xFF); + bytes[ header.length_offset ] = ( (width >> 8) & 0xFF); + bytes[ header.length_offset + 1] = (width & 0xFF); + + // Back to a full JPEG now. + return arrayBufferToBase64( bytes ); + }; + + /** + * Render an image into a Canvas + * + * @param {HTMLCanvasElement} canvas Canvas element to render into + * @param {list} image 3-tuple of base64-encoded image data, width, height + * @param {list} final Final width and height + */ + var render = function (canvas, image, final, cb) { + var ctx = canvas.getContext('2d'), + width = parseInt( final[0] ), + height = parseInt( final[1] ), + radius = parseInt( final[2] ); + + // Ensure smoothing is off + ctx.mozImageSmoothingEnabled = false; + ctx.webkitImageSmoothingEnabled = false; + ctx.msImageSmoothingEnabled = false; + ctx.imageSmoothingEnabled = false; + + var img = new Image(); + img.src = 'data:image/jpg;base64,' + reconstituteImage(header, image); + img.onload = function () { + canvas.width = width; + canvas.height = height; + + ctx.drawImage(img, 0, 0, width, height); + StackBlur.canvasRGB( canvas, 0, 0, width, height, radius ); + cb(); + }; + }; + + /** + * Render placeholder for an image + * + * @param {HTMLImageElement} element Element to render placeholder for + */ + var handleElement = function (element) { + if ( ! ( 'gaussholder' in element.dataset ) ) { + return; + } + + var canvas = document.createElement('canvas'); + var final = element.dataset.gaussholderSize.split(','); + + // Set the dimensions... + element.style.width = final[0] + 'px'; + element.style.height = final[1] + 'px'; + + // ...then recalculate based on what it actually renders as + var original = [ final[0], final[1] ]; + if ( element.width < final[0] ) { + // Rescale, keeping the aspect ratio + final[0] = element.width; + final[1] = final[1] * ( final[0] / original[0] ); + } else if ( element.height < final[1] ) { + // Rescale, keeping the aspect ratio + final[1] = element.height; + final[0] = final[0] * ( final[1] / original[1] ); + } + + // Set dimensions, _again_ + element.style.width = final[0] + 'px'; + element.style.height = final[1] + 'px'; + + render(canvas, element.dataset.gaussholder.split(','), final, function () { + // Load in as our background image + element.style.backgroundImage = 'url("' + canvas.toDataURL() + '")'; + element.style.backgroundRepeat = 'no-repeat'; + }); + }; + + var loadOriginal = function (element) { + if ( ! ( 'originalsrc' in element.dataset ) && ! ( 'originalsrcset' in element.dataset ) ) { + return; + } + + var data = element.dataset.gaussholderSize.split(','), + radius = parseInt( data[2] ); + + // Load our image now + var img = new Image(); + + if ( element.dataset.originalsrc ) { + img.src = element.dataset.originalsrc; + } + if ( element.dataset.originalsrcset ) { + img.srcset = element.dataset.originalsrcset; + } + + img.onload = function () { + // Filter property to use + var filterProp = ( 'webkitFilter' in element.style ) ? 'webkitFilter' : 'filter'; + element.style[ filterProp ] = 'blur(' + radius * 0.5 + 'px)'; + + // Ensure blur doesn't bleed past image border + element.style.clipPath = 'url(#gaussclip)'; // Current FF + element.style.clipPath = 'inset(0)'; // Standard + element.style.webkitClipPath = 'inset(0)'; // WebKit + + // Set the actual source + element.src = img.src; + element.srcset = img.srcset; + + // Cleaning source + element.dataset.originalsrc = ''; + element.dataset.originalsrcset = ''; + + // Clear placeholder temporary image + // (We do this after setting the source, as doing it before can + // cause a tiny flicker) + element.style.backgroundImage = ''; + element.style.backgroundRepeat = ''; + + var start = 0; + var anim = function (ts) { + if ( ! start ) start = ts; + var diff = ts - start; + if ( diff > fadeDuration ) { + element.style[ filterProp ] = ''; + element.style.clipPath = ''; + element.style.webkitClipPath = ''; + return; + } + + var effectiveRadius = radius * ( 1 - ( diff / fadeDuration ) ); + + element.style[ filterProp ] = 'blur(' + effectiveRadius * 0.5 + 'px)'; + window.requestAnimationFrame(anim); + }; + window.requestAnimationFrame(anim); + }; + }; + + var loadLazily = []; + var threshold = 1200; + var lastRun = 0, + loopTimeout = null; + + var scrollHandler = function () { + var now = Date.now(); + if ( ( lastRun + 40 ) > now ) { + if ( loopTimeout ) { + return; + } + loopTimeout = window.setTimeout(scrollHandler, 40); + return; + } + lastRun = now; + loopTimeout && (loopTimeout = null); + + var next = []; + for (var i = loadLazily.length - 1; i >= 0; i--) { + var img = loadLazily[i]; + var shouldShow = img.getBoundingClientRect().top <= ( window.innerHeight + threshold ); + if ( ! shouldShow ) { + next.push(img); + continue; + } + + loadOriginal(img); + } + loadLazily = next; + if (loadLazily.length < 1) { + window.removeEventListener('scroll', scrollHandler); + } + }; + + /** + * Render all placeholders on the page + */ + var handleAll = function () { + var images = document.getElementsByTagName('img'); + + for (var i = images.length - 1; i >= 0; i--) { + var img = images[i]; + + // Ensure the blank GIF has loaded first + if ( img.complete ) { + handleElement(img); + } else { + img.onload = function () { + handleElement(this); + } + } + } + + loadLazily = images; + scrollHandler(); + + if (loadLazily.length > 0) { + window.addEventListener('scroll', scrollHandler); + } + }; + + return handleAll; +})(window.GaussholderHeader); diff --git a/assets/gaussholder.min.js b/assets/gaussholder.min.js new file mode 100644 index 0000000..c5d5f62 --- /dev/null +++ b/assets/gaussholder.min.js @@ -0,0 +1 @@ +var StackBlur=function(){var T=[512,512,456,512,328,456,335,512,405,328,271,456,388,335,292,512,454,405,364,328,298,271,496,456,420,388,360,335,312,292,273,512,482,454,428,405,383,364,345,328,312,298,284,271,259,496,475,456,437,420,404,388,374,360,347,335,323,312,302,292,282,273,265,512,497,482,468,454,441,428,417,405,394,383,373,364,354,345,337,328,320,312,305,298,291,284,278,271,265,259,507,496,485,475,465,456,446,437,428,420,412,404,396,388,381,374,367,360,354,347,341,335,329,323,318,312,307,302,297,292,287,282,278,273,269,265,261,512,505,497,489,482,475,468,461,454,447,441,435,428,422,417,411,405,399,394,389,383,378,373,368,364,359,354,350,345,341,337,332,328,324,320,316,312,309,305,301,298,294,291,287,284,281,278,274,271,268,265,262,259,257,507,501,496,491,485,480,475,470,465,460,456,451,446,442,437,433,428,424,420,416,412,408,404,400,396,392,388,385,381,377,374,370,367,363,360,357,354,350,347,344,341,338,335,332,329,326,323,320,318,315,312,310,307,304,302,299,297,294,292,289,287,285,282,280,278,275,273,271,269,267,265,263,261,259],U=[9,11,12,13,13,14,14,15,15,15,15,16,16,16,16,17,17,17,17,17,17,17,18,18,18,18,18,18,18,18,18,19,19,19,19,19,19,19,19,19,19,19,19,19,19,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24];function q(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}return{canvasRGB:function(t,e,n,a,r,i){if(!(isNaN(i)||i<1)){i|=0;var s=function(t,e,n,a,r){if("string"==typeof t)t=document.getElementById(t);else if(!t instanceof HTMLCanvasElement)return;var i,s=t.getContext("2d");try{i=s.getImageData(e,n,a,r)}catch(t){throw new Error("unable to access image data: "+t)}return i}(t,e,n,a,r);s=function(t,e,n,a,r,i){var s,o,l,g,d,c,u,h,f,w,m,v,b,p,y,x,I,k,E,C,S=t.data,B=i+i+1,R=a-1,A=r-1,L=i+1,P=L*(L+1)/2,D=new q,F=D;for(l=1;l>N,S[c+1]=f*H>>N,S[c+2]=w*H>>N,h-=m,f-=v,w-=b,m-=_.r,v-=_.g,b-=_.b,g=u+((g=s+i+1)>N,S[g+1]=f*H>>N,S[g+2]=w*H>>N,h-=m,f-=v,w-=b,m-=_.r,v-=_.g,b-=_.b,g=s+((g=o+L)>8&255,s[t.height_offset+1]=255&r,s[t.length_offset]=a>>8&255,s[t.length_offset+1]=255&a,function(t){for(var e="",n=new Uint8Array(t),a=n.byteLength,r=0;r> shg_sum; + pixels[yi+1] = (g_sum * mul_sum) >> shg_sum; + pixels[yi+2] = (b_sum * mul_sum) >> shg_sum; + + r_sum -= r_out_sum; + g_sum -= g_out_sum; + b_sum -= b_out_sum; + + r_out_sum -= stackIn.r; + g_out_sum -= stackIn.g; + b_out_sum -= stackIn.b; + + p = (yw + ((p = x + radius + 1) < widthMinus1 ? p : widthMinus1)) << 2; + + r_in_sum += (stackIn.r = pixels[p]); + g_in_sum += (stackIn.g = pixels[p+1]); + b_in_sum += (stackIn.b = pixels[p+2]); + + r_sum += r_in_sum; + g_sum += g_in_sum; + b_sum += b_in_sum; + + stackIn = stackIn.next; + + r_out_sum += (pr = stackOut.r); + g_out_sum += (pg = stackOut.g); + b_out_sum += (pb = stackOut.b); + + r_in_sum -= pr; + g_in_sum -= pg; + b_in_sum -= pb; + + stackOut = stackOut.next; + + yi += 4; + } + yw += width; + } + + + for (x = 0; x < width; x++) + { + g_in_sum = b_in_sum = r_in_sum = g_sum = b_sum = r_sum = 0; + + yi = x << 2; + r_out_sum = radiusPlus1 * (pr = pixels[yi]); + g_out_sum = radiusPlus1 * (pg = pixels[yi+1]); + b_out_sum = radiusPlus1 * (pb = pixels[yi+2]); + + r_sum += sumFactor * pr; + g_sum += sumFactor * pg; + b_sum += sumFactor * pb; + + stack = stackStart; + + for (i = 0; i < radiusPlus1; i++) + { + stack.r = pr; + stack.g = pg; + stack.b = pb; + stack = stack.next; + } + + yp = width; + + for (i = 1; i <= radius; i++) + { + yi = (yp + x) << 2; + + r_sum += (stack.r = (pr = pixels[yi])) * (rbs = radiusPlus1 - i); + g_sum += (stack.g = (pg = pixels[yi+1])) * rbs; + b_sum += (stack.b = (pb = pixels[yi+2])) * rbs; + + r_in_sum += pr; + g_in_sum += pg; + b_in_sum += pb; + + stack = stack.next; + + if(i < heightMinus1) + { + yp += width; + } + } + + yi = x; + stackIn = stackStart; + stackOut = stackEnd; + for (y = 0; y < height; y++) + { + p = yi << 2; + pixels[p] = (r_sum * mul_sum) >> shg_sum; + pixels[p+1] = (g_sum * mul_sum) >> shg_sum; + pixels[p+2] = (b_sum * mul_sum) >> shg_sum; + + r_sum -= r_out_sum; + g_sum -= g_out_sum; + b_sum -= b_out_sum; + + r_out_sum -= stackIn.r; + g_out_sum -= stackIn.g; + b_out_sum -= stackIn.b; + + p = (x + (((p = y + radiusPlus1) < heightMinus1 ? p : heightMinus1) * width)) << 2; + + r_sum += (r_in_sum += (stackIn.r = pixels[p])); + g_sum += (g_in_sum += (stackIn.g = pixels[p+1])); + b_sum += (b_in_sum += (stackIn.b = pixels[p+2])); + + stackIn = stackIn.next; + + r_out_sum += (pr = stackOut.r); + g_out_sum += (pg = stackOut.g); + b_out_sum += (pb = stackOut.b); + + r_in_sum -= pr; + g_in_sum -= pg; + b_in_sum -= pb; + + stackOut = stackOut.next; + + yi += width; + } + } + + return imageData; + } + + function BlurStack() + { + this.r = 0; + this.g = 0; + this.b = 0; + this.a = 0; + this.next = null; + } + + return { + canvasRGB: processCanvasRGB + }; +})(); diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..bb20bfc --- /dev/null +++ b/composer.json @@ -0,0 +1,28 @@ +{ + "name": "humanmade/gaussholder", + "description": "Fast and lightweight image previews for WordPress", + "license": "GPL-2.0-or-later", + "authors": [ + { + "name": "Contributors", + "homepage": "https://github.com/humanmade/Gaussholder/graphs/contributors" + } + ], + "type": "wordpress-plugin", + "minimum-stability": "dev", + "prefer-stable": true, + "support": { + "wiki": "https://github.com/humanmade/Gaussholder/wiki", + "source": "https://github.com/humanmade/Gaussholder/releases", + "issues": "https://github.com/humanmade/Gaussholder/issues" + }, + "keywords": [ + "wordpress", + "plugin", + "images" + ], + "require": { + "php": ">=5.3", + "composer/installers": "~1.0" + } +} diff --git a/gaussholder.php b/gaussholder.php new file mode 100644 index 0000000..ff868b9 --- /dev/null +++ b/gaussholder.php @@ -0,0 +1,37 @@ +[data-slug="gaussholder"] .plugin-version-author-uri:after { content: "Made with \002764\00FE0F, just for you."; font-size: 0.8em; opacity: 0; float: right; transition: 300ms opacity; } [data-slug="gaussholder"]:hover .plugin-version-author-uri:after { opacity: 0.3; }'; + }); +} diff --git a/inc/class-plugin.php b/inc/class-plugin.php new file mode 100644 index 0000000..7ab39e8 --- /dev/null +++ b/inc/class-plugin.php @@ -0,0 +1,230 @@ + blur radius. + * + * By default, Gaussholder won't generate any placeholders, and you need to + * opt-in to using it. Simply filter here, and add the size names for what + * you want generated. + * + * Be aware that for every size you add, a placeholder will be generated and + * stored in the database. If you have a lot of sizes, this will be a _lot_ + * of data. + * + * The blur radius controls how much blur we use. The image is pre-scaled + * down by this factor, and this is really the key to how the placeholders + * work. Increasing radius decreases the required data quadratically: a + * radius of 2 uses a quarter as much data as the full image; a radius of + * 8 uses 1/64 the amount of data. (Due to compression, the final result + * will _not_ follow this scaling.) + * + * Be careful tuning this, as decreasing the radius too much will cause a + * huge amount of data in the body; increasing it will end up with not + * enough data to be an effective placeholder. + * + * The radius needs to be tuned to each size individually. Ideally, you want + * to keep it to about 200 bytes of data for the placeholder. + * + * (Also note: changing the radius requires regenerating the + * placeholder data.) + * + * @param string[] $enabled Enabled sizes. + */ + return apply_filters( 'gaussholder.image_sizes', array() ); +} + +function get_blur_radius() { + /** + * Filter the blur radius. + * + * The blur radius controls how much blur we use. The image is pre-scaled + * down by this factor, and this is really the key to how the placeholders + * work. Increasing radius decreases the required data quadratically: a + * radius of 2 uses a quarter as much data as the full image; a radius of + * 8 uses 1/64 the amount of data. (Due to compression, the final result + * will _not_ follow this scaling.) + * + * Be careful tuning this, as decreasing the radius too much will cause a + * huge amount of data in the body; increasing it will end up with not + * enough data to be an effective placeholder. + * + * (Also note: changing this requires regenerating the placeholder data.) + * + * @param int $radius Blur radius in pixels. + */ + return apply_filters( 'gaussholder.blur_radius', 16 ); +} + +/** + * Get the blur radius for a given size. + * + * @param string $size Image size to get radius for. + * @return int|null Radius in pixels if enabled, null if size isn't enabled. + */ +function get_blur_radius_for_size( $size ) { + $sizes = get_enabled_sizes(); + if ( ! isset( $sizes[ $size ] ) ) { + return null; + } + + return absint( $sizes[ $size ] ); +} + +/** + * Is the size enabled for placeholders? + * + * @param string $size Image size to check. + * @return boolean True if enabled, false if not. Simple. + */ +function is_enabled_size( $size ) { + return in_array( $size, array_keys( get_enabled_sizes() ) ); +} + +/** + * Get a placeholder for an image. + * + * @param int $id Attachment ID. + * @param string $size Image size. + * @return string + */ +function get_placeholder( $id, $size ) { + if ( ! is_enabled_size( $size ) ) { + return null; + } + + $meta = get_post_meta( $id, META_PREFIX . $size, true ); + if ( empty( $meta ) ) { + return null; + } + + return $meta; +} + +/** + * Schedule a background task to generate placeholders. + * + * @param array $metadata + * @param int $attachment_id + * @return array + */ +function queue_generate_placeholders_on_save( $metadata, $attachment_id ) { + // Is this a JPEG? + $mime_type = get_post_mime_type( $attachment_id ); + if ( ! in_array( $mime_type, array( 'image/jpg', 'image/jpeg' ) ) ) { + return $metadata; + } + + wp_schedule_single_event( time() + 5, 'gaussholder.generate_placeholders', [ $attachment_id ] ); + + return $metadata; +} + +/** + * Save extracted colors to image metadata + * + * @param $metadata + * @param $attachment_id + * + * @return mixed + */ +function generate_placeholders( $attachment_id ) { + // Is this a JPEG? + $mime_type = get_post_mime_type( $attachment_id ); + if ( ! in_array( $mime_type, array( 'image/jpg', 'image/jpeg' ) ) ) { + return; + } + + $sizes = get_enabled_sizes(); + foreach ( $sizes as $size => $radius ) { + $data = generate_placeholder( $attachment_id, $size, $radius ); + if ( empty( $data ) ) { + continue; + } + + // Comma-separated data, width, and height + $for_database = sprintf( '%s,%d,%d', base64_encode( $data[0] ), $data[1], $data[2] ); + update_post_meta( $attachment_id, META_PREFIX . $size, $for_database ); + } +} + +/** + * Get data for a given image size. + * + * @param string $size Image size. + * @return array|null Image size data (with `width`, `height`, `crop` keys) on success, null if image size is invalid. + */ +function get_size_data( $size ) { + global $_wp_additional_image_sizes; + + switch ( $size ) { + case 'thumbnail': + case 'medium': + case 'large': + $size_data = array( + 'width' => get_option( "{$size}_size_w" ), + 'height' => get_option( "{$size}_size_h" ), + 'crop' => get_option( "{$size}_crop" ), + ); + break; + + default: + if ( ! isset( $_wp_additional_image_sizes[ $size ] ) ) { + return null; + } + + $size_data = $_wp_additional_image_sizes[ $size ]; + break; + } + + return $size_data; +} + +/** + * Generate a placeholder at a given size. + * + * @param int $id Attachment ID. + * @param string $size Image size. + * @param int $radius Blur radius. + * @return array|null 3-tuple of binary image data (string), width (int), height (int) on success; null on error. + */ +function generate_placeholder( $id, $size, $radius ) { + $size_data = get_size_data( $size ); + if ( $size !== 'full' && empty( $size_data ) ) { + _doing_it_wrong( __FUNCTION__, __( 'Invalid image size enabled for placeholders', 'gaussholder' ), '1.0.0' ); + return null; + } + + $uploads = wp_upload_dir(); + $img = wp_get_attachment_image_src( $id, $size ); + + // Pass image paths directly to data_for_file. + if ( strpos( $img[0], $uploads['baseurl'] ) === 0 ) { + $path = str_replace( $uploads['baseurl'], $uploads['basedir'], $img[0] ); + return JPEG\data_for_file( $path, $radius ); + } + + // If the image url wp_get_attachment_image_src is not a local url (for example), + // using Tachyon or Photon, download the file to temp before passing it to data_for_file. + // This is needed because IMagick can not handle remote files, and we specifically want + // to use the remote file rather than mapping it to an image on disk, as the remote + // service such as Tachyon may look different (smart dropping, image filters) etc. + $path = download_url( $img[0] ); + if ( is_wp_error( $path ) ) { + return; + } + $data = JPEG\data_for_file( $path, $radius ); + unlink( $path ); + return $data; +} diff --git a/inc/class-wp-cli-command.php b/inc/class-wp-cli-command.php new file mode 100644 index 0000000..4b6fc63 --- /dev/null +++ b/inc/class-wp-cli-command.php @@ -0,0 +1,153 @@ + [--dry-run] [--verbose] [--regenerate] + */ + public function process( $args, $args_assoc ) { + + $args_assoc = wp_parse_args( $args_assoc, array( + 'verbose' => true, + 'dry-run' => false, + 'regenerate' => false, + ) ); + + $attachment_id = absint( $args[0] ); + $metadata = wp_get_attachment_metadata( $attachment_id ); + + if ( ! $args_assoc['regenerate'] ) { + return; + } + + // Unless regenerating, skip attachments that already have data. + $has_placeholder = false; + if ( ! $args_assoc['regenerate'] && $has_placeholder ) { + + if ( $args_assoc['verbose'] ) { + WP_CLI::line( sprintf( 'Skipping attachment %d. Data already exists.', $attachment_id ) ); + } + + return; + + } + + if ( ! $args_assoc['dry-run'] ) { + generate_placeholders( $attachment_id ); + } + + if ( $args_assoc['verbose'] ) { + WP_CLI::line( sprintf( 'Updated caclulated colors for attachment %d.', $attachment_id ) ); + } + + } + + /** + * Process image color data for all attachments. + * + * @subcommand process-all + * @synopsis [--dry-run] [--count=] [--offset=] [--regenerate] + */ + public function process_all( $args, $args_assoc ) { + + $args_assoc = wp_parse_args( $args_assoc, array( + 'count' => 1, + 'offset' => 0, + 'dry-run' => false, + 'regenerate' => false, + ) ); + + if ( empty( $page ) ) { + $page = absint( $args_assoc['offset'] ) / absint( $args_assoc['count'] ); + $page = ceil( $page ); + if ( $page < 1 ) { + $page = 1; + } + } + + while ( empty( $no_more_posts ) ) { + + $query = new WP_Query( array( + 'post_type' => 'attachment', + 'post_status' => 'inherit', + 'fields' => 'ids', + 'posts_per_page' => $args_assoc['count'], + 'paged' => $page, + ) ); + + if ( empty( $progress_bar ) ) { + $progress_bar = new cli\progress\Bar( sprintf( 'Processing images', absint( $query->found_posts ) ), absint( $query->found_posts ), 100 ); + $progress_bar->display(); + } + + foreach ( $query->posts as $post_id ) { + + $progress_bar->tick(); + + $this->process( + array( $post_id ), + array( + 'verbose' => false, + 'dry-run' => $args_assoc['dry-run'], + 'regenerate' => $args_assoc['regenerate'] + ) + ); + + } + + if ( $query->get('paged') >= $query->max_num_pages ) { + $no_more_posts = true; + } + + if ( $query->get('paged') === 0 ) { + $page = 2; + } else { + $page = absint( $query->get('paged') ) + 1; + } + + } + + $progress_bar->finish(); + + } + + /** + * Check how big the placeholder will be for an image or file with a given + * radius. + * + * @subcommand check-size + * @synopsis + * @param array $args + */ + public function check_size( $args ) { + if ( is_numeric( $args[0] ) ) { + $attachment_id = absint( $args[0] ); + $file = get_attached_file( $attachment_id ); + if ( empty( $file ) ) { + WP_CLI::error( __( 'Attachment does not exist', 'gaussholder' ) ); + } + } else { + $file = $args[1]; + } + + if ( ! file_exists( $file ) ) { + WP_CLI::error( sprintf( __( 'File %s does not exist', 'gaussholder' ), $file ) ); + } + + // Generate a placeholder with the radius + $radius = absint( $args[1] ); + $data = JPEG\data_for_file( $file, $radius ); + WP_CLI::line( sprintf( '%s: %dB (%dpx radius)', basename( $file ), strlen( $data[0] ), $radius ) ); + } + +} diff --git a/inc/frontend/namespace.php b/inc/frontend/namespace.php new file mode 100644 index 0000000..4d335f8 --- /dev/null +++ b/inc/frontend/namespace.php @@ -0,0 +1,179 @@ +'; + + // Output header onto the page + $header = JPEG\build_header(); + $header['header'] = base64_encode( $header['header'] ); + echo 'var GaussholderHeader = ' . json_encode( $header ) . ";\n"; + + foreach ( $files as $file ) { + echo file_get_contents( $file ) . "\n"; + } + + echo 'Gaussholder();'; + + // Clipping path for Firefox compatibility on fade in + echo ''; +} + +/** + * Mangle tags in the post content. + * + * Replaces the tag src to stop browsers loading the source early, as well + * as adding the Gaussholder data. + * @param [type] $content [description] + * @return [type] [description] + */ +function mangle_images( $content ) { + // Find images + $searcher = '#]+(?:class=[\'"]([^\'"]*wp-image-(\d+)[^\'"]*)|data-gaussholder-id="(\d+)")[^>]+>#x'; + if ( ! preg_match_all( $searcher, $content, $images, PREG_SET_ORDER ) ) { + return $content; + } + + $blank = file_get_contents( Gaussholder\PLUGIN_DIR . '/assets/blank.gif' ); + $blank_url = 'data:image/gif;base64,' . base64_encode( $blank ); + + foreach ( $images as $image ) { + $tag = $image[0]; + if ( ! empty( $image[2] ) ) { + // Singular image, using `class="wp-image-"` + $id = $image[2]; + $class = $image[1]; + + // Attempt to get the image size from a size class. + if ( ! preg_match( '#\bsize-([\w-]+)\b#', $class, $size_match ) ) { + // If we don't have a size class, the only other option is to search + // all the URLs for image sizes that we support, and see if the src + // attribute matches. + preg_match( '#\bsrc=[\'|"]([^\'"]*)#', $tag, $src_match ); + $all_sizes = array_keys( Gaussholder\get_enabled_sizes() ); + foreach ( $all_sizes as $single_size ) { + $url = wp_get_attachment_image_src( $id, $single_size ); + // WordPress applies esc_attr (and sometimes esc_url) to all image attributes, + // so we have decode entities when making a comparison. + if ( $url[0] === html_entity_decode( $src_match[1] ) ) { + $size = $single_size; + break; + } + } + // If we still were not able to find the image size from the src + // attribute, then skip this image. + if ( ! isset( $size ) ) { + continue; + } + } else { + $size = $size_match[1]; + } + } else { + // Gallery, using `data-gaussholder-id=""` + $id = $image[3]; + if ( ! preg_match( '# class=[\'"][^\'"]*\battachment-([\w-]+)\b#', $tag, $size_match ) ) { + continue; + } + $size = $size_match[1]; + } + + if ( ! Gaussholder\is_enabled_size( $size ) ) { + continue; + } + + $new_attrs = array(); + + // Replace src with our blank GIF + $new_attrs[] = 'src="' . esc_attr( $blank_url ) . '"'; + + // Remove srcset + $new_attrs[] = 'srcset=""'; + + // Add the actual placeholder + $placeholder = Gaussholder\get_placeholder( $id, $size ); + $new_attrs[] = 'data-gaussholder="' . esc_attr( $placeholder ) . '"'; + + // Add final size + $size_data = Gaussholder\get_size_data( $size ); + $radius = Gaussholder\get_blur_radius_for_size( $size ); + + // Has the size been overridden? + if ( preg_match( '#height=[\'"](\d+)[\'"]#i', $tag, $matches ) ) { + $size_data['height'] = absint( $matches[1] ); + } + if ( preg_match( '#width=[\'"](\d+)[\'"]#i', $tag, $matches ) ) { + $size_data['width'] = absint( $matches[1] ); + } + $new_attrs[] = sprintf( + 'data-gaussholder-size="%s,%s,%s"', + $size_data['width'], + $size_data['height'], + $radius + ); + + $mangled_tag = str_replace( + array( + ' srcset="', + ' src="', + ), + array( + 'data-originalsrcset="', + ' ' . implode( ' ', $new_attrs ) . ') data-originalsrc="', + ), + $tag + ); + + $content = str_replace( $tag, $mangled_tag, $content ); + } + + return $content; +} + +/** + * Adds a style attribute to image HTML. + * + * @param $attr + * @param $attachment + * @param $size + * + * @return mixed + */ +function add_placeholder_to_attributes( $attr, $attachment, $size ) { + // Are placeholders enabled for this size? + if ( ! Gaussholder\is_enabled_size( $size ) ) { + return $attr; + } + + $attr['data-gaussholder-id'] = $attachment->ID; + + return $attr; +} diff --git a/inc/jpeg/namespace.php b/inc/jpeg/namespace.php new file mode 100644 index 0000000..f38e01e --- /dev/null +++ b/inc/jpeg/namespace.php @@ -0,0 +1,222 @@ +readImageBlob( file_get_contents( $file ) ); + } else { + $editor = new Imagick( $file ); + } + + $size = $editor->getImageGeometry(); + + // Normalise the density to 72dpi + $editor->setImageResolution( 72, 72 ); + + // Set sampling factors to constant + $editor->setSamplingFactors(array('1x1', '1x1', '1x1')); + + // Ensure we use default Huffman tables + $editor->setOption('jpeg:optimize-coding', false); + + // Strip unnecessary header data + $editor->stripImage(); + + // Adjust by scaling factor + $width = floor( $size['width'] / $radius ); + $height = floor( $size['height'] / $radius ); + $editor->scaleImage( $width, $height ); + + $scaled = $editor->getImageBlob(); + + // Strip the header + $scaled_stripped = substr( $scaled, strpos( $scaled, "\xFF\xDA" ) + 2 ); + + return array( $scaled_stripped, $width, $height ); +} diff --git a/preview.gif b/preview.gif new file mode 100644 index 0000000..5c89275 Binary files /dev/null and b/preview.gif differ