implement caching of scaled images.

This commit is contained in:
Isaac Connor 2016-05-02 14:12:30 -04:00
parent fe63e4af80
commit 240d08133d
1 changed files with 38 additions and 20 deletions

View File

@ -135,27 +135,45 @@ if ( $errorText ) {
Error("No bytes read from ". $Storage->Path() . '/'.$path ); Error("No bytes read from ". $Storage->Path() . '/'.$path );
} }
} else { } else {
Error("Doing a scaled image: scale($scale) width($width) height($height)"); Debug("Doing a scaled image: scale($scale) width($width) height($height)");
$i = imagecreatefromjpeg ( $Storage->Path().'/'.$path ); $i = 0;
$oldWidth=imagesx($i); if ( ! ( $width && $height ) ) {
$oldHeight=imagesy($i); $i = imagecreatefromjpeg( $Storage->Path().'/'.$path );
if($width==0 && $height==0) // scale has to be set to get here with both zero $oldWidth = imagesx( $i );
{ $oldHeight = imagesy( $i );
$width = $oldWidth * $scale / 100.0; if ( $width == 0 && $height == 0 ) { // scale has to be set to get here with both zero
$height= $oldHeight * $scale / 100.0; $width = $oldWidth * $scale / 100.0;
} elseif ($width==0 && $height!=0) { $height= $oldHeight * $scale / 100.0;
$width = ($height * $oldWidth) / $oldHeight; } elseif ( $width == 0 && $height != 0 ) {
} elseif ($width!=0 && $height==0) { $width = ($height * $oldWidth) / $oldHeight;
$height = ($width * $oldHeight) / $oldWidth; } elseif ( $width != 0 && $height == 0 ) {
$height = ($width * $oldHeight) / $oldWidth;
}
if ( $width == $oldWidth && $height == $oldHeight) {
Warning( "No change to width despite scaling." );
}
} }
if($width==$oldWidth && $height==$oldHeight) {// See if we really need to scale
imagejpeg($i); # Slight optimisation, thumbnails always specify width and height, so we can cache them.
imagedestroy($i); $scaled_path = $Storage->Path().'/'.preg_replace('/\.jpg$/', "-${width}x${height}.jpg", $path );
} else { // we do need to scale if ( file_exists( $scaled_path ) ) {
$iScale = imagescale($i, $width, $height); Debug( "Using cached scaled image at $scaled_path.");
imagejpeg($iScale); if ( ! readfile( $Storage->Path().'/'.$path. "-${width}x${height}" ) ) {
imagedestroy($i); Error("No bytes read from ". $Storage->Path() . '/'.$path );
imagedestroy($iScale); }
} else {
Debug( "Cached scaled image does not exist at $scaled_path. Creating it");
ob_start();
if ( ! $i )
$i = imagecreatefromjpeg( $Storage->Path().'/'.$path );
$iScale = imagescale( $i, $width, $height );
imagejpeg( $iScale );
imagedestroy( $i );
imagedestroy( $iScale );
$scaled_jpeg_data = ob_get_contents();
file_put_contents( $scaled_path, $scaled_jpeg_data );
ob_end_clean();
echo $scaled_jpeg_data;
} }
} }
} }