creating thumbnail and add background to make 933*335 size for slider (to avoid streching an image)

StackOverflow https://stackoverflow.com/questions/22128099

Question

/*Creating thumbnail and I want to resize an image to 933*335. Let's say the image will then be 513*335, because its not rectangular. How can I add a white or black background so that the resulting image is 933*335? Is this possible with thumbnail guide me for that*/ function make_thumb($src, $dest, $desired_height = 335, $ext) {

if ($ext == 'jpg' || $ext == 'jpeg') { $source_image = imagecreatefromjpeg($src);  }
if ($ext == 'png') { $source_image = imagecreatefrompng($src); }
if ($ext == 'gif') { $source_image = imagecreatefromgif($src); }   

/* read the source image */
$width = imagesx($source_image);
$height = imagesy($source_image);

/* calc the new width */
$desired_width = floor($width * ($desired_height / $height));

/* create a new, "virtual" image */
$virtual_image = imagecreatetruecolor($desired_width, $desired_height);

/* copy source image at a resized size */
imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);

/* create the physical thumbnail image to its destination */

if ($ext == 'jpg' || $ext == 'jpeg') { imagejpeg($virtual_image, $dest); }
if ($ext == 'png') { imagepng($virtual_image, $dest); }
if ($ext == 'gif') { imagegif($virtual_image, $dest); }   

} this is code for creating a thumbnail but i want to 933*335 without streching an image

Was it helpful?

Solution

//function for creating an thumbnail   
 private function _generateThumb() {
switch($this->imageType) {
        case 'jpg':
            $image = @imagecreatefromjpeg($this->pathToImage);
        break;
        case 'gif':
        $image = @imagecreatefromgif($this->pathToImage);
        break;
        case 'png':
            $image = @imagecreatefrompng($this->pathToImage);
        break;
}

if ($image === false) {
    trigger_error('image could not be created', 1024);
    print 'nöööööö'; exit;
}
$thumbImage = @ImageCreateTrueColor(933, $this->thumbHeight);

//select background color using number between 0 to 255
$color = imagecolorallocate($thumbImage,0,0,0);//black color
imagefill($thumbImage, 0, 0, $color);

if ($this->imageType == 'png' || $this->imageType == 'gif')
{
imagealphablending($thumbImage, false);

$s=933-$this->thumbWidth;
$s=$s/2;//to keep image in center i.e distance from x-axis
ImageCopyResampled($thumbImage, $image,$s,0,0,0, $this->thumbWidth, $this->thumbHeight,$this->imageWidth, $this->imageHeight);

}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top