Skip to content

Commit

Permalink
Build changes from 2879dee
Browse files Browse the repository at this point in the history
  • Loading branch information
CircleCI committed Apr 29, 2019
0 parents commit a8c9f36
Show file tree
Hide file tree
Showing 13 changed files with 1,571 additions and 0 deletions.
55 changes: 55 additions & 0 deletions 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.
97 changes: 97 additions & 0 deletions README.md
@@ -0,0 +1,97 @@
<table width="100%">
<tr>
<td align="left" width="70">
<strong>Gaussholder</strong><br />
Fast and lightweight image previews, using Gaussian blur.
</td>
<td align="right" width="20%">
<!--
<a href="https://travis-ci.org/humanmade/Gaussholder">
<img src="https://travis-ci.org/humanmade/Gaussholder.svg?branch=master" alt="Build status">
</a>
<a href="http://codecov.io/github/humanmade/Gaussholder?branch=master">
<img src="http://codecov.io/github/humanmade/Gaussholder/coverage.svg?branch=master" alt="Coverage via codecov.io" />
</a>
-->
</td>
</tr>
<tr>
<td>
A <strong><a href="https://hmn.md/">Human Made</a></strong> project. Maintained by @rmccue.
</td>
<td align="center">
<img src="https://hmn.md/content/themes/hmnmd/assets/images/hm-logo.svg" width="100" />
</td>
</tr>
</table>

Gaussholder is an image placeholder utility, generating accurate preview images using an amazingly small amount of data.

<img src="preview.gif" />

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 <id_or_image> <radius>`. 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/)
Binary file added assets/blank.gif
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
231 changes: 231 additions & 0 deletions 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);

0 comments on commit a8c9f36

Please sign in to comment.