Skip to content

Instantly share code, notes, and snippets.

@swalkinshaw
Created June 15, 2013 15:16
Show Gist options
  • Save swalkinshaw/5788453 to your computer and use it in GitHub Desktop.
Save swalkinshaw/5788453 to your computer and use it in GitHub Desktop.
<?php
/*
Plugin Name: Image Optimizer
Plugin URI:
Description: Automatically optimizes images using jpegtran and optipng on upload
Version: 0.1
Author: Scott Walkinshaw
Author URI:
Support URI:
*/
class OptiImg {
function __construct() {
add_filter('wp_generate_attachment_metadata', array($this, 'generate_attachment_metadata'), 1);
add_action('add_attachment', array($this, 'optimize_attachment'), 1);
}
/**
* Generate attachment metadata filter
*
* Upload _wp_attachment_metadata
*
* @param array $metadata
* @return array
*/
public function generate_attachment_metadata($metadata) {
$images = $this->get_metadata_files($metadata);
foreach($images as $image) {
$result = $this->optimize_image($image);
}
return $metadata;
}
/**
* Returns base file path of attachment
* @param string $attached_file
* @return string
*/
public function filepath($attached_file) {
$upload_dir = wp_upload_dir();
return $upload_dir['basedir'] . '/' . $attached_file;
}
/**
* Returns array of files from sizes array
*
* @param string $attached_file
* @param array $sizes
* @return array
*/
public function get_thumbnails($attached_file, $thumbnails) {
$files = array();
$base_dir = str_replace(strrchr($attached_file, '/'), '', $attached_file) . '/';
$original_image_path = $this->filepath($attached_file);
$files[] = $original_image_path;
foreach ((array) $thumbnails as $thumbnail) {
if (isset($thumbnail['file'])) {
$files[] = $this->filepath($base_dir . $thumbnail['file']);
}
}
return $files;
}
/**
* Returns attachment files by metadata
*
* @param array $metadata
* @return array
*/
public function get_metadata_files($metadata) {
$files = array();
if (isset($metadata['file']) && isset($metadata['sizes'])) {
$files = array_merge($files, $this->get_thumbnails($metadata['file'], $metadata['sizes']));
}
return $files;
}
/**
* Optimize image file with jpegtran or optipng
*
* @param string $image
* @return boolean
*/
public function optimize_image($image) {
$type = getimagesize($image);
if ($type !== false) {
$type = $type['mime'];
} else {
return false;
}
switch ($type) {
case 'image/jpeg':
case 'image/jpg':
exec("/usr/local/bin/jpegtran -copy none -optimize -outfile {$image} {$image}");
break;
case 'image/png':
case 'image/gif':
exec("/usr/local/bin/optipng -o7 {$image}");
break;
default:
return false;
}
return true;
}
/**
* Optimize image file by attachment id
*
* @param integer $attachment_id
* @return boolean
*/
public function optimize_attachment($attachment_id) {
$image = get_attached_file($attachment_id);
return $this->optimize_image($image);
}
}
$opti_img = new OptiImg();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment