Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php imagecopyresampled adds black background

Tags:

php

resize

gd

I have a resize image script that takes a 130x81 image and adds it to a 130x130 image, when the imagecopyresampled function runs it adds a black background into the space that is left over, even though the base image is white. Code below, I could really appreciate some help.

The image I am trying to merge onto the 130x130 file php created is: 130x81 image

$width = 130;
$height = 130;
$filename = 'process-add.jpg'; //130x81px jpg
$this->_image = imagecreatefromjpeg($filename);

$background = imagecreatetruecolor(130,130);//create the background 130x130
$whiteBackground = imagecolorallocate($background, 255, 255, 255); 
imagefill($background,0,0,$whiteBackground); // fill the background with white

imagecopyresampled($background, $this->_image,(130-$width)/2,(130-$height)/2, 0, 0, $width, $height, $width, $height); // copy the image to the background

ImageJpeg ($background,null,100); //display

I have read on multiple posts to add:

imagealphablending($background, false);

into the code which should fix it, but it doesn't make any difference.

Thanks in advance!

like image 529
Scott Avatar asked Jul 16 '13 09:07

Scott


1 Answers

This has been solved. The issue was with teh width and height on the imagecopyresampled call. See the code block below:

<?

ini_set('allow_url_fopen', true);
$filename = 'http://img.yessy.com/1402152287-17201a.jpg'; // 130x81
$image = imagecreatefromjpeg($filename);
list($originalWidth, $originalHeight) = getimagesize($filename);

// Size of image to create
$width = 130;
$height = 130;

$background = imagecreatetruecolor($width, $height);//create the background 130x130
$whiteBackground = imagecolorallocate($background, 255, 255, 255); 
imagefill($background,0,0,$whiteBackground); // fill the background with white

imagecopyresampled($background, $image, 0, ($height - $originalHeight) / 2, 0, 0, $originalWidth, $originalHeight, $originalWidth, $originalHeight); // copy the image to the background

header("Content-type: image/jpeg");
ImageJpeg ($background,null,100); //display
?>
like image 122
Scott Avatar answered Sep 20 '22 22:09

Scott