shibbir ahmed shibbir ahmed - 3 months ago 24
PHP Question

why image background color is showing me blurry when I crop the image using PHP?

I am using following php function to crop a image. When a image is cropped then the image background is look like a blurry. Like bellow image. It's should be solid white background color :

Blurry Image :

enter image description here

Php code is bellow :

function crop_image ($target, $newcopy, $w, $h, $ext) {

$ext = strtolower($ext);
if ($ext == "gif"){
$image = imagecreatefromgif($target);
} else if($ext =="png"){
$image = imagecreatefrompng($target);
} else {
$image = imagecreatefromjpeg($target);
}

$filename = $newcopy;
$thumb_width = $w;
$thumb_height = $h;
$width = imagesx($image);
$height = imagesy($image);
$original_aspect = $width / $height;
$thumb_aspect = $thumb_width / $thumb_height;
if ( $original_aspect >= $thumb_aspect )
{
$new_height = $thumb_height;
$new_width = $width / ($height / $thumb_height);
}
else
{
$new_width = $thumb_width;
$new_height = $height / ($width / $thumb_width);
}
$thumb = imagecreatetruecolor( $thumb_width, $thumb_height );
$color = imagecolorallocate($thumb, 255, 255, 255);
imagefill($thumb, 0, 0, $color);

imagecopyresampled($thumb,
$image,
0 - ($new_width - $thumb_width) / 2, // Center the image horizontally
0 - ($new_height - $thumb_height) / 2, // Center the image vertically
0, 0,
$new_width, $new_height,
$width, $height);
imagejpeg($thumb, $filename, 80);

}

Answer

You're feeding a $quality value of 80 into imagejpeg. JPEG is a lossy format. This results in artifacts like the ones you're seeing:

quality is optional, and ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file). The default is the default IJG quality value (about 75).

Try using a higher value:

imagejpeg($thumb, $filename, 90);

The maximum value for $quality is 100.