Skip to content

Instantly share code, notes, and snippets.

@pdbreen
Created April 27, 2023 14:46
Show Gist options
  • Save pdbreen/c72d2ec2a4e796bc2e74237474561120 to your computer and use it in GitHub Desktop.
Save pdbreen/c72d2ec2a4e796bc2e74237474561120 to your computer and use it in GitHub Desktop.
cacheImageGd
public static function cacheImageGd(Filesystem $cache, $imageData, int $w, int $h, string $jpegName, string $webpName)
{
$srcImage = imagecreatefromstring($imageData);
$srcWidth = imagesx($srcImage);
$srcHeight = imagesy($srcImage);
$widthRatio = $w / $srcWidth;
$heightRatio = $h / $srcHeight;
$x = $y = 0;
if ($w == 0) {
// Scale based on height
$height = $h;
$width = $w = round($heightRatio * $srcWidth);
} elseif ($h == 0) {
// Scale based on width
$width = $w;
$height = $h = round($widthRatio * $srcHeight);
} elseif ($widthRatio < $heightRatio) {
$width = round($widthRatio * $srcWidth);
$height = round($widthRatio * $srcHeight);
$y = ($h - $height) / 2;
} else {
$width = round($heightRatio * $srcWidth);
$height = round($heightRatio * $srcHeight);
$x = ($w - $width) / 2;
}
$copy = imagecreatetruecolor((int) $w, (int) $h);
/** @psalm-suppress InvalidArgument */
imageinterlace($copy, true);
// Background to white!
$whiteBackground = imagecolorallocate($copy, 255, 255, 255);
imagefill($copy, 0, 0, $whiteBackground);
imagecopyresampled($copy, $srcImage, (int) $x, (int) $y, 0, 0, (int) $width, (int) $height, $srcWidth, $srcHeight);
imagedestroy($srcImage);
// Sharpen - From intervention image
$amount = 10;
$min = $amount >= 10 ? $amount * -0.01 : 0;
$max = $amount * -0.025;
$abs = ((4 * $min + 4 * $max) * -1) + 1;
$divisor = 1;
$sharpenMatrix = [
[$min, $max, $min],
[$max, $abs, $max],
[$min, $max, $min],
];
imageconvolution($copy, $sharpenMatrix, $divisor, 0);
ob_start();
imagejpeg($copy, null, self::IMAGE_QUALITY);
$jpegData = ob_get_contents();
ob_end_clean();
if (! empty($jpegData)) {
// Remove current if exists
if ($cache->exists($jpegName)) {
$cache->delete($jpegName);
}
$cache->put($jpegName, $jpegData);
self::logInfo("{$jpegName} created");
$errorData = [];
if (function_exists('imagewebp')) {
ob_start();
imagewebp($copy, null, self::IMAGE_QUALITY);
$webpData = ob_get_contents();
ob_end_clean();
}
if (! empty($webpData)) {
// Remove current if exists
if ($cache->exists($webpName)) {
$cache->delete($webpName);
}
$cache->put($webpName, $webpData);
self::logInfo("{$webpName} created");
unset($webpData);
} else {
self::logError("Failed to create {$webpName}", $errorData);
}
// Cleanup
unset($jpegData);
Storage::disk('local')->delete("images/{$jpegName}");
Storage::disk('local')->delete("images/{$webpName}");
} else {
self::logError("Failed to create {$jpegName}");
}
imagedestroy($copy);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment