Posts tagged ‘thumbnail’

Easy Image Class

I needed something simple to grab images from MySQL database and display them. Slowly it grew into a very handy class.

This class can be used to manipulate images stored in files or in a MySQL database. It can read images from files and store them in a MySQL database table, and vice-versa. The class can also convert images between GIF, JPEG and PNG formats, as well resize the images to create thumbnails.

Documentation:
Coming Soon…

Image Thumbnail / Resize Function

Log time ago I wrote this function for my friend’s gallery website. The function is straight forward and uses the GD library of PHP. You may resize the image by giving it the maximum width and height you want the thumbnail to have. The function acts as an extension of the GD library so to speak, so you have to pass the image resource. An additional argument may be passed stating if you want the thumbnail to be square or not, by default it is false. If it is true the width:height ratio will not be change, it only fills the empty space with black color and places the thumbnail image in the center of the square.

imagethumb(image resource, max width, max height, fill to make square)
1 – (GD image resource) Straight forward teh image resource loaded by GD library.
2 – (int) maximum width of thumbnail
3 – (int) maximum width of thumbnail
4 – (true/false) make thumbnail square

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
function imagethumb($old_im, $limit_w = 100, $limit_h = 100, $fill = false)
{
	//get original dimensions
	$old_w = imagesx($old_im);
	$old_h = imagesy($old_im);
 
	//first resize by width if overflow else set old to new
	if($old_w > $limit_w)
	{
		//get reduction percent
		$reduce_percent = ($limit_w / $old_w) * 100;
		//set new w and h
		$new_w = ($old_w / 100) * $reduce_percent;
		$new_h = ($old_h / 100) * $reduce_percent;
	}
	else
	{
		//set as the old dimensions
		$new_w = $old_w;
		$new_h = $old_h;
	}
 
	//second resize by height if still overflows
	if($new_h > $limit_h)
	{
		//get reduction percent
		$reduce_percent = ($limit_h / $new_h) * 100;
		//set new w and h
		$new_w = ($new_w / 100) * $reduce_percent;
		$new_h = ($new_h / 100) * $reduce_percent;
	}
 
	if($fill == true)
	{
		//height offset picture, to keep centered
		if($new_h < $limit_h)
			$h_offset = floor(($limit_h - $new_h)/2);
		else
			$h_offset = 0;
 
		//width offset picture, to keep centered
		if($new_w < $limit_w)
			$w_offset = floor(($limit_w - $new_w)/2);
		else
			$w_offset = 0;
 
		//make new image and copy to it
		$new_im = imagecreatetruecolor($limit_w, $limit_h);
	}
	else
		$new_im = imagecreatetruecolor($new_w, $new_h);
 
	imagecopyresampled($new_im, $old_im, $w_offset, $h_offset, 0, 0, $new_w, $new_h, $old_w, $old_h);
 
	return $new_im;
}