Created
April 12, 2016 15:34
-
-
Save Fil/d5c57c49ef07f6ff4400cdcdf8b5051c to your computer and use it in GitHub Desktop.
recompress jpg files on the fly
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
pour l'installer, assurez-vous d'avoir un executable jpeg-recompress a l'emplacement indiqué, | |
et copier dans .htaccess les lignes suivantes | |
RewriteCond %{REQUEST_FILENAME} \.jpg | |
RewriteCond %{DOCUMENT_ROOT}/jpeg-recompress.php -f | |
RewriteRule \.jpg$ ./jpeg-recompress.php [QSA,L] | |
*/ | |
define('_JPEG_RECOMPRESS', '/var/alternc/exec.usr/jpeg-recompress'); | |
define('_CACHE', 'tmp/jpeg-recompress/'); | |
$ori = '.' . preg_replace('/(\?.*|\.\.)/', '', $_SERVER['REQUEST_URI']); | |
$err = array(); | |
$file = null; | |
if (!file_exists($ori) || !is_readable($ori)) { | |
$err[] = "$ori inexistant"; | |
@header("HTTP/1.0 404 Not Found"); | |
#@header('Content-Type: image/jpeg'); | |
echo join("\n",$err); | |
exit; | |
} | |
$file = $ori; | |
$time = filemtime($ori); | |
if (!is_dir(_CACHE) and !mkdir(_CACHE) and !is_writeable(_CACHE)) { | |
$err[] = "erreur cache"; | |
$file = $ori; | |
} else if (preg_match('/raw/', $_SERVER['REQUEST_URI'])) { | |
$file = $ori; | |
} else { | |
$md = md5($ori); | |
$dir = _CACHE.substr($md,0,2).'/'; | |
if (!is_dir($dir)) mkdir ($dir); | |
$dest = $dir.md5($ori).'-'.basename($ori, '.jpg') . '.jpg'; | |
if (!file_exists($dest) or (filemtime($dest) <= $time)) { | |
touch ($dest); | |
$_ori = escapeshellarg($ori); | |
$_dest = escapeshellarg($dest); | |
$c = _JPEG_RECOMPRESS . " --accurate --quality high --no-copy $_ori $_dest"; | |
$a = `$c &`; | |
} | |
if (filesize($dest) > 0 ) { | |
$file = $dest; | |
} | |
} | |
if ($file !== $ori) { | |
$mf = @filesize($file); $mo = @filesize($ori); $ratio = sprintf("%.2d", 100*$mf/$mo); | |
$log = "$file ($mf) = $ori ($mo) ; $ratio%"; | |
error_log($log."\n", 3, _CACHE.'jpeg-recompress.log'); | |
} | |
@header('Content-Type: image/jpeg'); | |
@header('Last-Modified: '.gmdate('D, d M Y H:i:s T', $time)); | |
readfile($file); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment