Resize image to specific dimensions using php

What is GD Library

GD Library is PHP lilbrary which help us to manipulate images using their inbuilt functions.

Resize Images using PHP and GD Library

While working on website some time we need to resize images to specific dimension without stretching the image.
We can achieve by using GD library and little custom code. It will add white spaces on sides if image is not properly proportioned. Code is below

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
function resizeImage($source_path='',$target='',$height='',$width='',$newimage = '')
{
	$urltarget = 'http://example.com/images/resized/'.$newimage; /** this will be target url to be used **/
	if(!file_exists($target)){
		list($source_width, $source_height, $source_type) = getimagesize($source_path);
		switch ($source_type) {
			case IMAGETYPE_GIF:
				$source_gdim = imagecreatefromgif($source_path);
				break;
			case IMAGETYPE_JPEG:
				$source_gdim = imagecreatefromjpeg($source_path);
				break;
			case IMAGETYPE_JPG:
				$source_gdim = imagecreatefromjpeg($source_path);
				break;
			case IMAGETYPE_PNG:
				$source_gdim = imagecreatefrompng($source_path);
				break;
		}
		$source_aspect_ratio = $source_width / $source_height;
		$desired_aspect_ratio = $width / $height;
 
		if($source_height>$source_width){
		  $percent=(($source_width/$source_height)*100);
		  $twidth=(int)(($height*$percent)/100);
		  $theight=$height;
 
		}else if($source_width>$source_height){
		  $percent=(($source_height/$source_width)*100);
		  $theight=(int)(($width*$percent)/100);
		  $twidth=$width;
		}else{
		  $twidth=$width;
		  $theight=$height;
		}
		$temp_gdim = imagecreatetruecolor($twidth, $theight);
		ImageCopyResampled(
				$temp_gdim,
				$source_gdim,
				0, 0,
				0, 0,
				$twidth, $theight,
				$source_width, $source_height
		);
		if($twidth>$theight){
		  $y0=(int)(($height/2) - ($theight/2));
		  $x0=0;
		}else if($theight>$twidth){
		  $x0=(int)(($width/2) - ($twidth/2));
		  $y0=0;
		}else{
		  $x0=0;
		  $y0=0;
		}
 
		$desired_gdim = imagecreatetruecolor($width, $height);
		$whiteBackground = imagecolorallocate($desired_gdim, 255, 255, 255);
		imagefill($desired_gdim,0,0,$whiteBackground);
 
		imagecopy(
				$desired_gdim,
				$temp_gdim,
				$x0, $y0,
				0,0,
				$twidth, $theight
 
		);
		imagejpeg($desired_gdim,$target,100);
				return $urltarget;
	}
	else{
			return $urltarget;
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *


*