Skip to content

Instantly share code, notes, and snippets.

@CodeBrauer
Last active June 16, 2016 08:54
Show Gist options
  • Save CodeBrauer/e9cd8fb70344dce23642e084f929606e to your computer and use it in GitHub Desktop.
Save CodeBrauer/e9cd8fb70344dce23642e084f929606e to your computer and use it in GitHub Desktop.
Blur image dynamically
<?php
/**
* Strong Blur
*
* @param resource $gdImageResource
* @param int $blurFactor optional
* This is the strength of the blur
* 0 = no blur, 3 = default, anything over 5 is extremely blurred
* @return GD image resource
* @author Martijn Frazer, idea based on http://stackoverflow.com/a/20264482
*/
function blur($gdImageResource, $blurFactor = 3)
{
$blurFactor = round($blurFactor);
$originalWidth = imagesx($gdImageResource);
$originalHeight = imagesy($gdImageResource);
$smallestWidth = ceil($originalWidth * pow(0.5, $blurFactor));
$smallestHeight = ceil($originalHeight * pow(0.5, $blurFactor));
$prevImage = $gdImageResource;
$prevWidth = $originalWidth;
$prevHeight = $originalHeight;
for($i = 0; $i < $blurFactor; $i += 1)
{
$nextWidth = $smallestWidth * pow(2, $i);
$nextHeight = $smallestHeight * pow(2, $i);
$nextImage = imagecreatetruecolor($nextWidth, $nextHeight);
imagecopyresized($nextImage, $prevImage, 0, 0, 0, 0, $nextWidth, $nextHeight, $prevWidth, $prevHeight);
imagefilter($nextImage, IMG_FILTER_GAUSSIAN_BLUR);
$prevImage = $nextImage;
$prevWidth = $nextWidth;
$prevHeight = $nextHeight;
}
imagecopyresized($gdImageResource, $nextImage, 0, 0, 0, 0, $originalWidth, $originalHeight, $nextWidth, $nextHeight);
imagefilter($gdImageResource, IMG_FILTER_GAUSSIAN_BLUR);
imagedestroy($prevImage);
return $gdImageResource;
}
$im = imagecreatefromjpeg($_GET['href']);
header('Content-Type: image/jpeg');
blur($im, 4);
imagejpeg($im);
imagedestroy($im);
@CodeBrauer
Copy link
Author

Example usage:

http://localhost/blur.php?href=https://placebear.com/400/200

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment