Skip to content

Commit

Permalink
Build changes from eba394e
Browse files Browse the repository at this point in the history
CircleCI committed Oct 26, 2022
0 parents commit 41663ae
Showing 32 changed files with 1,923 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"presets": ["@babel/preset-env"]
}
31 changes: 31 additions & 0 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
version: 2
jobs:
build:
docker:
- image: circleci/php:7.3-node

branches:
only:
# Whitelist branches to build for.
- master
steps:
# Checkout repo & subs:
- checkout

# Get npm cache:
- restore_cache:
key: npm

# Build steps:
- run: npm install
- run: npm run build

# Make fast:
- save_cache:
key: npm
paths:
- ~/.npm

# Run the deploy:
- deploy:
command: .circleci/deploy.sh
13 changes: 13 additions & 0 deletions .circleci/deploy-exclude.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Add files or patterns to exclude from the built branch here.
# Consult the "INCLUDE/EXCLUDE PATTERN RULES" section of the rsync manual for
# supported patterns.
#
# Note: Excluding ".circleci" will cause your branch to fail. Use the
# `branches` option in config.yml instead.

.git
.gitignore
Gruntfile.js
node_modules
package.json
package-lock.json
95 changes: 95 additions & 0 deletions .circleci/deploy.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
#!/bin/bash -e
#
# Deploy your branch.
#

DEPLOY_SUFFIX="${DEPLOY_SUFFIX:--built}"
GIT_USER="${DEPLOY_GIT_USER:-CircleCI}"
GIT_EMAIL="${DEPLOY_GIT_EMAIL:-rob+platform-ui-build@hmn.md}"

BRANCH="${CIRCLE_BRANCH}"
SRC_DIR="$PWD"
BUILD_DIR="/tmp/hm-build"

if [[ -z "$BRANCH" ]]; then
echo "No branch specified!"
exit 1
fi

if [[ -d "$BUILD_DIR" ]]; then
echo "WARNING: ${BUILD_DIR} already exists. You may have accidentally cached this"
echo "directory. This will cause issues with deploying."
exit 1
fi

COMMIT=$(git rev-parse HEAD)
VERSION=$(grep 'Version: ' gaussholder.php | grep -oEi '[0-9\.a-z\+-]+$')

if [[ $VERSION != "null" ]]; then
DEPLOY_BRANCH="${VERSION}--branch"
DEPLOY_AS_RELEASE="${DEPLOY_AS_RELEASE:-yes}"
else
DEPLOY_BRANCH="${BRANCH}${DEPLOY_SUFFIX}"
DEPLOY_AS_RELEASE="${DEPLOY_AS_RELEASE:-no}"
fi

echo "Deploying $BRANCH to $DEPLOY_BRANCH"

# If the deploy branch doesn't already exist, create it from the empty root.
if ! git rev-parse --verify "remotes/origin/$DEPLOY_BRANCH" >/dev/null 2>&1; then
echo -e "\nCreating $DEPLOY_BRANCH..."
git worktree add --detach "$BUILD_DIR"
cd "$BUILD_DIR"
git checkout --orphan "$DEPLOY_BRANCH"
else
echo "Using existing $DEPLOY_BRANCH"
git worktree add --detach "$BUILD_DIR" "remotes/origin/$DEPLOY_BRANCH"
cd "$BUILD_DIR"
git checkout "$DEPLOY_BRANCH"
fi

# Ensure we're in the right dir
cd "$BUILD_DIR"

# Remove existing files
git rm -rfq .

# Sync built files
echo -e "\nSyncing files..."
if ! command -v 'rsync'; then
sudo apt-get update
sudo apt-get install -q -y rsync
fi

rsync -av "$SRC_DIR/" "$BUILD_DIR" --exclude-from "$SRC_DIR/.circleci/deploy-exclude.txt"

# Add changed files
git add .

if [ -z "$(git status --porcelain)" ]; then
echo "No changes to built files."
exit
fi

# Print status!
echo -e "\nSynced files. Changed:"
git status -s

# Double-check our user/email config
if ! git config user.email; then
git config user.name "$GIT_USER"
git config user.email "$GIT_EMAIL"
fi

# Commit it.
MESSAGE=$( printf 'Build changes from %s\n\n%s' "${COMMIT}" "${CIRCLE_BUILD_URL}" )
git commit -m "$MESSAGE"

# Push it (real good).
git push origin "$DEPLOY_BRANCH"

# Make a release if one doesn't exist.
if [[ $DEPLOY_AS_RELEASE = "yes" && $(git tag -l "$VERSION") != $VERSION ]]; then
git tag "$VERSION"
git push origin "$VERSION"
fi
3 changes: 3 additions & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules
assets/src/stackblur.js
dist
3 changes: 3 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "@humanmade"
}
20 changes: 20 additions & 0 deletions .webpack/webpack.config.common.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

module.exports = {
entry: [ './assets/index.js' ],
output: {
filename: 'gaussholder.min.js',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
loader: 'babel-loader',
},
],
},
plugins: [
new CleanWebpackPlugin(),
],
};
21 changes: 21 additions & 0 deletions .webpack/webpack.config.dev.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
const common = require( './webpack.config.common' );

module.exports = {
...common,
mode: 'development',
devtool: 'inline-source-map',
module: {
...common.module,
rules: [
...common.module.rules,
{
test: /\.js?$/,
exclude: /(node_modules|bower_components)/,
enforce: 'pre',
loader: require.resolve( 'eslint-loader' ),
options: {},
},
]

}
};
6 changes: 6 additions & 0 deletions .webpack/webpack.config.prod.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
const common = require( './webpack.config.common' );

module.exports = {
...common,
mode: 'production',
};
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Changelog

- Bug: Fix stray characters in img tag attributes #47
25 changes: 25 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Contributing

To get started follow these steps:

1. `git clone git@github.com:humanmade/gaussholder.git` or fork the repository and clone your fork.
1. `cd gaussholder`
1. `npm install`
1. `npm run build` (to build the assets)

You should then start working on your fork or branch.

## Making a pull request

When you make a pull request it will be reviewed. You should also update the `CHANGELOG.md` - add lines after the title such as `- Bug: Fixed a typo #33` to describe each change and link to the issues if applicable.

## Making a new release

1. Create a new branch
2. Update the version number in the comment header of `plugin.php` to reflect the nature of the changes, this plugin follows semver versioning.
- For small changes like bug fixes update the patch version
- For changes that add functionality without changing existing functionality update the minor version
- For breaking or highly significant changes update the major version
3. Add a title heading for the version number above the latest updates in `CHANGELOG.md`
4. Create a pull request for the branch
5. Once merged a release will be built and deployed by CircleCI corresponding to the version number in `plugin.php`
55 changes: 55 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -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.
99 changes: 99 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
<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.

By default Gaussholder is initialized with the `DOMContentLoaded` event. Should you need to reinitialize Gaussholder after the page had loaded, this can be achieved with `GaussHolder();`.

### 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
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
6 changes: 6 additions & 0 deletions assets/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import Gaussholder from './src/gaussholder';

document.addEventListener( 'DOMContentLoaded', Gaussholder );

// Add the Gaussholder function to the window object.
window.GaussHolder = Gaussholder;
21 changes: 21 additions & 0 deletions assets/src/gaussholder.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import handleElement from './handlers/handle-element';
import intersectionHandler from './handlers/intersection-handler';
import scrollHandler from './handlers/scroll-handler';

/**
* Initializes Gaussholder.
*/
export default function () {
const images = document.getElementsByTagName( 'img' );

if ( typeof IntersectionObserver === 'undefined' ) {
// Old browser. Handle events based on scrolling.
scrollHandler( images );
} else {
// Use the Intersection Observer API.
intersectionHandler( images );
}

// Initialize all images.
Array.prototype.slice.call( images ).forEach( handleElement );
}
43 changes: 43 additions & 0 deletions assets/src/handlers/handle-element.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import renderImageIntoCanvas from '../render-image-into-canvas';

/**
* Render placeholder for an image
*
* @param {HTMLImageElement} element Element to render placeholder for
*/
let handleElement = function ( element ) {
if ( ! ( 'gaussholder' in element.dataset ) ) {
return;
}

let canvas = document.createElement( 'canvas' );
let 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
let 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';

renderImageIntoCanvas( canvas, element.dataset.gaussholder.split( ',' ), final, function () {
// Load in as our background image
element.style.backgroundImage = 'url("' + canvas.toDataURL() + '")';
element.style.backgroundRepeat = 'no-repeat';
} );
};

export default handleElement;
27 changes: 27 additions & 0 deletions assets/src/handlers/intersection-handler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import loadImageCallback from '../load-original';

/**
* Handles the images on screen by using the Intersection Observer API.
*
* @param {NodeList} images List of images in DOM to handle.
*/
const intersectionHandler = function ( images ) {
const options = {
rootMargin: '1200px', // Threshold that Intersection API uses to detect the intersection between the image and the main element in the page.
};

const imagesObserver = new IntersectionObserver( entries => {
const visibleImages = entries.filter( ( { isIntersecting } ) => isIntersecting === true );

visibleImages.forEach( ( { target } ) => {
loadImageCallback( target );
imagesObserver.unobserve( target );
} );
}, options );

Array.from( images ).forEach( img => {
imagesObserver.observe( img );
} );
};

export default intersectionHandler;
45 changes: 45 additions & 0 deletions assets/src/handlers/scroll-handler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import loadImageCallback from '../load-original';
import throttle from '../throttle';

let loadLazily = [];

/**
* Handle images when scrolling. Suitable for older browsers.
*/
const scrollHandler = function () {
let threshold = 1200;
let next = [];
for ( let i = loadLazily.length - 1; i >= 0; i-- ) {
let img = loadLazily[i];
let shouldShow = img.getBoundingClientRect().top <= ( window.innerHeight + threshold );
if ( ! shouldShow ) {
next.push( img );
continue;
}

loadImageCallback( img );
}
loadLazily = next;
};

/**
* Scroll handle initialization.
*
* @param {NodeList} images List of images on screen.
*/
const init = function ( images ) {
loadLazily = images;

const throttledHandler = throttle( scrollHandler, 40 );
scrollHandler();
window.addEventListener( 'scroll', throttledHandler );

const finishedTimeoutCheck = window.setInterval( function () {
if ( loadLazily.length < 1 ) {
window.removeEventListener( 'scroll', throttledHandler );
window.clearInterval( finishedTimeoutCheck );
}
}, 1000 );
};

export default init;
78 changes: 78 additions & 0 deletions assets/src/load-original.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// Fade duration in ms when the image loads in.
const FADE_DURATION = 800;

/**
* Load the original image. Triggered once the image is on the viewport.
*
* @param {Node} element Image element
*/
let loadOriginal = function ( element ) {
if ( ! ( 'originalsrc' in element.dataset ) && ! ( 'originalsrcset' in element.dataset ) ) {
return;
}

let data = element.dataset.gaussholderSize.split( ',' ),
radius = parseInt( data[2] );

// Load our image now
let 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
let 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 = '';

let start = 0;

/**
* @param {number} ts Timestamp.
*/
const anim = function ( ts ) {
if ( ! start ) start = ts;
let diff = ts - start;
if ( diff > FADE_DURATION ) {
element.style[ filterProp ] = '';
element.style.clipPath = '';
element.style.webkitClipPath = '';
return;
}

let effectiveRadius = radius * ( 1 - ( diff / FADE_DURATION ) );

element.style[ filterProp ] = 'blur(' + effectiveRadius * 0.5 + 'px)';
window.requestAnimationFrame( anim );
};
window.requestAnimationFrame( anim );
};
};

export default loadOriginal;
43 changes: 43 additions & 0 deletions assets/src/reconstitute-image.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/**
* @param {number} buffer Buffer Size.
*
* @returns {string} Base64 string.
*/
function arrayBufferToBase64( buffer ) {
let binary = '';
let bytes = new Uint8Array( buffer );
let len = bytes.byteLength;
for ( let i = 0; i < len; i++ ) {
binary += String.fromCharCode( bytes[ i ] );
}
return window.btoa( binary );
}

/**
* @param {*} header Gaussholder header.
* @param {Array} image Image node.
*
* @returns {string} Base 64 string
*/
function reconstituteImage( header, image ) {
let image_data = image[0],
width = parseInt( image[1] ),
height = parseInt( image[2] );

let full = atob( header.header ) + atob( image_data );
let bytes = new Uint8Array( full.length );
for ( let 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 );
}

export default reconstituteImage;
41 changes: 41 additions & 0 deletions assets/src/render-image-into-canvas.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import reconstituteImage from './reconstitute-image';
import StackBlur from './stackblur';

const { GaussholderHeader } = window;

/**
* Render an image into a Canvas
*
* @param {HTMLCanvasElement} canvas Canvas element to render into
* @param {Array} image 3-tuple of base64-encoded image data, width, height
* @param {Array} final Final width and height
* @param {Function} cb Callback
*/
function renderImageIntoCanvas( canvas, image, final, cb ) {
let 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;

let img = new Image();
img.src = 'data:image/jpg;base64,' + reconstituteImage( GaussholderHeader, 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();
};
}

export default renderImageIntoCanvas;
340 changes: 340 additions & 0 deletions assets/src/stackblur.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,340 @@
/*
StackBlur - a fast almost Gaussian Blur For Canvas
Version: 0.5
Author: Mario Klingemann
Contact: mario@quasimondo.com
Website: http://www.quasimondo.com/StackBlurForCanvas
Twitter: @quasimondo
In case you find this class useful - especially in commercial projects -
I am not totally unhappy for a small donation to my PayPal account
mario@quasimondo.de
Or support me on flattr:
https://flattr.com/thing/72791/StackBlur-a-fast-almost-Gaussian-Blur-Effect-for-CanvasJavascript
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.
*/

var StackBlur = (function () {
var mul_table = [
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];


var shg_table = [
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 getImageDataFromCanvas(canvas, top_x, top_y, width, height)
{
if (typeof(canvas) == 'string')
var canvas = document.getElementById(canvas);
else if (!canvas instanceof HTMLCanvasElement)
return;

var context = canvas.getContext('2d');
var imageData;

try {
// try {
imageData = context.getImageData(top_x, top_y, width, height);
/*} catch(e) {
// NOTE: this part is supposedly only needed if you want to work with local files
// so it might be okay to remove the whole try/catch block and just use
// imageData = context.getImageData(top_x, top_y, width, height);
try {
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
imageData = context.getImageData(top_x, top_y, width, height);
} catch(e) {
alert("Cannot access local image");
throw new Error("unable to access local image data: " + e);
return;
}
}*/
} catch(e) {
throw new Error("unable to access image data: " + e);
}

return imageData;
}

function processCanvasRGB(canvas, top_x, top_y, width, height, radius)
{
if (isNaN(radius) || radius < 1) return;
radius |= 0;

var imageData = getImageDataFromCanvas(canvas, top_x, top_y, width, height);
imageData = processImageDataRGB(imageData, top_x, top_y, width, height, radius);

canvas.getContext('2d').putImageData(imageData, top_x, top_y);
}

function processImageDataRGB(imageData, top_x, top_y, width, height, radius)
{
var pixels = imageData.data;

var x, y, i, p, yp, yi, yw, r_sum, g_sum, b_sum,
r_out_sum, g_out_sum, b_out_sum,
r_in_sum, g_in_sum, b_in_sum,
pr, pg, pb, rbs;

var div = radius + radius + 1;
var w4 = width << 2;
var widthMinus1 = width - 1;
var heightMinus1 = height - 1;
var radiusPlus1 = radius + 1;
var sumFactor = radiusPlus1 * (radiusPlus1 + 1) / 2;

var stackStart = new BlurStack();
var stack = stackStart;
for (i = 1; i < div; i++)
{
stack = stack.next = new BlurStack();
if (i == radiusPlus1) var stackEnd = stack;
}
stack.next = stackStart;
var stackIn = null;
var stackOut = null;

yw = yi = 0;

var mul_sum = mul_table[radius];
var shg_sum = shg_table[radius];

for (y = 0; y < height; y++)
{
r_in_sum = g_in_sum = b_in_sum = r_sum = g_sum = b_sum = 0;

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;
}

for (i = 1; i < radiusPlus1; i++)
{
p = yi + ((widthMinus1 < i ? widthMinus1 : i) << 2);
r_sum += (stack.r = (pr = pixels[p])) * (rbs = radiusPlus1 - i);
g_sum += (stack.g = (pg = pixels[p+1])) * rbs;
b_sum += (stack.b = (pb = pixels[p+2])) * rbs;

r_in_sum += pr;
g_in_sum += pg;
b_in_sum += pb;

stack = stack.next;
}


stackIn = stackStart;
stackOut = stackEnd;
for (x = 0; x < width; x++)
{
pixels[yi] = (r_sum * mul_sum) >> 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
};
});

export default StackBlur;
22 changes: 22 additions & 0 deletions assets/src/throttle.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
* See https://stackoverflow.com/questions/27078285/simple-throttle-in-js
*
* @param {Function} callback Function to throttle.
* @param {number} limit Throttle time
*
* @returns {function(): void} throttleled callback.
*/
const throttle = function ( callback, limit ) {
let waiting = false;
return function () {
if ( ! waiting ) {
callback.apply( this, arguments );
waiting = true;
setTimeout( function () {
waiting = false;
}, limit );
}
};
};

export default throttle;
28 changes: 28 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -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"
}
}
1 change: 1 addition & 0 deletions dist/gaussholder.min.js
37 changes: 37 additions & 0 deletions gaussholder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php
/**
* Plugin Name: Gaussholder
* Plugin URI: http://hmn.md/
* Description: Quick and beautiful image placeholders using Gaussian blur.
* Version: 1.1.6
* Author: Human Made
* Author URI: http://hmn.md/
* License: GPL-2.0+
* License URI: http://www.gnu.org/licenses/gpl-2.0.txt
* Network: true
*/

namespace Gaussholder;

use WP_CLI;

define( __NAMESPACE__ . '\\PLUGIN_DIR', __DIR__ );

require_once __DIR__ . '/inc/class-plugin.php';
require_once __DIR__ . '/inc/frontend/namespace.php';
require_once __DIR__ . '/inc/jpeg/namespace.php';

if ( defined( 'WP_CLI' ) && WP_CLI ) {
require_once __DIR__ . '/inc/class-wp-cli-command.php';
WP_CLI::add_command( 'gaussholder', 'Gaussholder\\CLI_Command' );
}

add_action( 'plugins_loaded', __NAMESPACE__ . '\\Frontend\\bootstrap' );
add_filter( 'wp_update_attachment_metadata', __NAMESPACE__ . '\\queue_generate_placeholders_on_save', 10, 2 );
add_action( 'gaussholder.generate_placeholders', __NAMESPACE__ . '\\generate_placeholders' );
// We <3 you!
if ( WP_DEBUG && ! defined( 'WP_I_AM_A_GRUMPY_PANTS' ) ) {
add_action( 'admin_head-plugins.php', function () {
echo '<style>[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; }</style>';
});
}
248 changes: 248 additions & 0 deletions inc/class-plugin.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,248 @@
<?php

namespace Gaussholder;

use WP_Error;

const META_PREFIX = 'gaussholder_';

/**
* Get sizes to use placeholders on.
*
* @return string[] List of enabled sizes.
*/
function get_enabled_sizes() {
/**
* Filter the sizes Gaussholder images will be generated for.
*
* This is a map of size name => 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 WP_Error|bool
*/
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 new WP_Error( 'image-not-jpg', 'Image is not a JPEG.' );
}

$errors = new WP_Error;

$sizes = get_enabled_sizes();
foreach ( $sizes as $size => $radius ) {
try {
$data = generate_placeholder( $attachment_id, $size, $radius );
} catch ( \ImagickException $e ) {
$errors->add( $size, sprintf( 'Unable to generate placeholder for %s (Imagick exception - %s)', $size, $e->getMessage() ) );
continue;
}

if ( empty( $data ) ) {
$errors->add( $size, sprintf( 'Unable to generate placeholder for %s', $size ) );
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 );
}

if ( $errors->has_errors() ) {
return $errors;
}

return true;
}

/**
* 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 ) ) {
trigger_error( sprintf( 'Error downloading image from %s: ', $img[0], $path->get_error_message() ), E_USER_WARNING );
return;
}
$data = JPEG\data_for_file( $path, $radius );
unlink( $path );
return $data;
}
157 changes: 157 additions & 0 deletions inc/class-wp-cli-command.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
<?php

namespace Gaussholder;

use cli;
use WP_CLI;
use WP_CLI_Command;
use WP_Query;

class CLI_Command extends WP_CLI_Command {

/**
* Calculate image color data for a single attachment.
*
* @subcommand process
* @synopsis <id> [--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'] ) {
$result = generate_placeholders( $attachment_id );
}

if ( is_wp_error( $result ) ) {
WP_CLI::error( implode( "\n", $result->get_error_messages() ) );
}

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=<int>] [--offset=<int>] [--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 [Total: %d]', absint( $query->found_posts ) ), absint( $query->found_posts ), 100 );
$progress_bar->display();
}

foreach ( $query->posts as $post_id ) {

$progress_bar->tick( 1, sprintf( 'Processing images [Total: %d / Processing ID: %d]', absint( $query->found_posts ), $post_id ) );

$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 <id_or_file> <radius>
* @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 ) );
}

}
187 changes: 187 additions & 0 deletions inc/frontend/namespace.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
<?php

namespace Gaussholder\Frontend;

use Gaussholder;
use Gaussholder\JPEG;

/**
* Set up hooked callbacks on plugins_loaded
*/
function bootstrap() {
add_action( 'wp_footer', __NAMESPACE__ . '\\output_script' );

add_filter( 'the_content', __NAMESPACE__ . '\\mangle_images', 30 );
add_filter( 'wp_get_attachment_image_attributes', __NAMESPACE__ . '\\add_placeholder_to_attributes', 10, 3 );
}

/**
* Output the Gaussholder script onto the page.
*/
function output_script() {
echo '<script>';

// Output header onto the page
$header = JPEG\build_header();
$header['header'] = base64_encode( $header['header'] );
echo 'var GaussholderHeader = ' . json_encode( $header ) . ";\n";

echo file_get_contents( Gaussholder\PLUGIN_DIR . '/dist/gaussholder.min.js' ) . "\n";

echo '</script>';

// Clipping path for Firefox compatibility on fade in
echo '<svg width="0" height="0" style="position: absolute"><clipPath id="gaussclip" clipPathUnits="objectBoundingBox"><rect width="1" height="1"></rect></clipPath></svg>';
}

/**
* Mangle <img> tags in the post content.
*
* Replaces the <img> 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 = '#<img[^>]+(?:class=[\'"]([^\'"]*wp-image-(\d+)[^\'"]*)|data-gaussholder-id="(\d+)")[^>]+>#x';
$preg_match_result = preg_match_all( $searcher, $content, $images, PREG_SET_ORDER );
/**
* Filter the regexp results when looking for images in a post content.
*
* By default, Gaussholder applies the $searcher regexp inside the_content filter callback. Some page builders
* manage images in different ways so the result could be false.
*
* This filter allows to change that result but also the images list generated by preg_match_all( $searcher, $content, $images, PREG_SET_ORDER )
* The $images parameter must be returned with the same format. That is:
*
* [
* 0 => Image tag (<img class="..." src="..." ... />)
* 1 => Image tag class
* 2 => Attachment ID
* ]
*/
$preg_match_result = apply_filters_ref_array( 'gaussholder.mangle_images_regexp_results', [ $preg_match_result, &$images, $content, $searcher ] );
if ( ! $preg_match_result ) {
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>"`
$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>"`
$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
$image_data = wp_get_attachment_image_src( $id, $size );
$size_data = [
'width' => $image_data[1],
'height' => $image_data[2],
];
$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;
}
222 changes: 222 additions & 0 deletions inc/jpeg/namespace.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,222 @@
<?php
/**
* Preview images before loading full detail
*
* Thanks to Facebook for their fantastic article inspiring this:
* https://code.facebook.com/posts/991252547593574/the-technology-behind-preview-photos/
*/

namespace Gaussholder\JPEG;

use Imagick;

/**
* Build a standard JFIF header
*
* @return array `header` element contains the JFIF header, `height_offset` contains the byte offset for the 2 height bytes, `length_offset` contains the byte offset for the 2 length bytes
*/
function build_header() {
// JFIF start of image
$header = "\xFF\xD8";

// Start JFIF-APP0 section
$header .= "\xFF\xE0";

// Header length (16 bytes)
$header .= "\x00\x10";

// Header ID: JFIF in ASCII with null terminator
$header .= "JFIF\x00";

// JFIF version (major minor)
$header .= "\x01\x01";

// Pixel density units:
// 00 = pixel aspect
// 01 = pixels per inch
// 02 = pixels per centimetre
$header .= "\x01";

// X density (72dpi)
$header .= "\x00\x48";

// Y density (72dpi)
$header .= "\x00\x48";

// X thumbnail size
$header .= "\x00";

// Y thumbnail size
$header .= "\x00";

// Start quantization table (table K.1)
$header .= "\xFF\xDB";
$header .= "\x00\x43\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\x0A\x07\x07\x06\x08\x0C\x0A\x0C\x0C\x0B\x0A\x0B\x0B\x0D\x0E\x12\x10\x0D\x0E\x11\x0E\x0B\x0B\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0C\x0F\x17\x18\x16\x14\x18\x12\x14\x15\x14";

// Another quantization table again? (table K.2)
$header .= "\xFF\xDB";
$header .= "\x00\x43\x01\x03\x04\x04\x05\x04\x05\x09\x05\x05\x09\x14\x0D\x0B\x0D\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14\x14";

// Start Of Frame
$header .= "\xFF\xC0";

// Frame length (17 bytes)
$header .= "\x00\x11";

// Sample precision
$header .= "\x08";

// Y size (in pixels, 2 bytes) *****CHANGE ME*****
$height_offset = strlen( $header );
$header .= "\xCA\xFE";

// X size (in pixels, 2 bytes) *****CHANGE ME*****
$length_offset = strlen( $header );
$header .= "\xDE\xAD";

// Nf - number of components (3 for coloured JPEG)
$header .= "\x03";

// For each component:

// Component 1
// Component ID
$header .= "\x01";

// H and V sampling (nibble for each)
$header .= "\x11";

// Quantization table number
$header .= "\x00";

// Component 2
// Component ID
$header .= "\x02";

// H and V sampling (nibble for each)
$header .= "\x11";

// Quantization table number
$header .= "\x01";

// Component 3
// Component ID
$header .= "\x03";

// H and V sampling (nibble for each)
$header .= "\x11";

// Quantization table number
$header .= "\x01";

// Huffman table from K.3.3.1 in JPEG specification: table K.3, luminance DC
$header .= "\xFF\xC4";

// Length (31 bytes)
$header .= "\x00\x1F";

// Information (0..3: number of tables, 4: type, 5..7: must be 0)
// Type DC, table 0
$header .= "\x00";

// Number of symbols
$header .= "\x00\x01\x05\x01\x01\x01\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00";

// Symbols!
$header .= "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B";

// Huffman table from K.3.3.2; table K.5, luminance AC
$header .= "\xFF\xC4";

// Length (181 bytes)
$header .= "\x00\xB5";

// Information (0..3: number, 4: type, 5..7: 0)
// Type AC, table 0
$header .= "\x10";

// Number of symbols
$header .= "\x00\x02\x01\x03\x03\x02\x04\x03\x05\x05\x04\x04\x00\x00\x01\x7D";

// Symbols!
$header .= "\x01\x02\x03\x00\x04\x11\x05\x12\x21\x31\x41\x06\x13\x51\x61\x07\x22\x71\x14\x32\x81\x91\xA1\x08\x23\x42\xB1\xC1\x15\x52\xD1\xF0\x24\x33\x62\x72\x82\x09\x0A\x16\x17\x18\x19\x1A\x25\x26\x27\x28\x29\x2A\x34\x35\x36\x37\x38\x39\x3A\x43\x44\x45\x46\x47\x48\x49\x4A\x53\x54\x55\x56\x57\x58\x59\x5A\x63\x64\x65\x66\x67\x68\x69\x6A\x73\x74\x75\x76\x77\x78\x79\x7A\x83\x84\x85\x86\x87\x88\x89\x8A\x92\x93\x94\x95\x96\x97\x98\x99\x9A\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA";

// Huffman table from K.3.3.1; table K.4, chrominance DC
$header .= "\xFF\xC4";

// Length (31 bytes)
$header .= "\x00\x1F";

// Information (0..3: number, 4: type, 5..7: 0)
// Type DC, table 1
$header .= "\x01";

// Number of symbols
$header .= "\x00\x03\x01\x01\x01\x01\x01\x01\x01\x01\x01\x00\x00\x00\x00\x00";

// Symbols!
$header .= "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B";

// Huffman table from K.3.3.2; table K.6, chrominance AC
$header .= "\xFF\xC4";

// Length (181 bytes)
$header .= "\x00\xB5";

// Information
// Type AC, table 1
$header .= "\x11";

// Number of symbols
$header .= "\x00\x02\x01\x02\x04\x04\x03\x04\x07\x05\x04\x04\x00\x01\x02\x77";

// Symbols!
$header .= "\x00\x01\x02\x03\x11\x04\x05\x21\x31\x06\x12\x41\x51\x07\x61\x71\x13\x22\x32\x81\x08\x14\x42\x91\xA1\xB1\xC1\x09\x23\x33\x52\xF0\x15\x62\x72\xD1\x0A\x16\x24\x34\xE1\x25\xF1\x17\x18\x19\x1A\x26\x27\x28\x29\x2A\x35\x36\x37\x38\x39\x3A\x43\x44\x45\x46\x47\x48\x49\x4A\x53\x54\x55\x56\x57\x58\x59\x5A\x63\x64\x65\x66\x67\x68\x69\x6A\x73\x74\x75\x76\x77\x78\x79\x7A\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x92\x93\x94\x95\x96\x97\x98\x99\x9A\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA";

// Start of Scan marker, get ready for an image!
$header .= "\xFF\xDA";

return compact( 'header', 'height_offset', 'length_offset' );
}

/**
* Get data for a file
*
* @param string $file Image file path
* @param int $radius Gaussian blur radius
* @return array 3-tuple of binary image data (string), width (int), and height (int).
*/
function data_for_file( $file, $radius ) {
if ( parse_url( $file, PHP_URL_SCHEME ) ) {
$editor = new Imagick();
$editor->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 );
}
Binary file added preview.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 41663ae

Please sign in to comment.