Image Upload and Re-size PHP
Sometimes you need to upload and resize image files using PHP, and here you will find the simplest PHP snippet that takes care of your uploaded image files. This snippet should work as it is, but there are several other methods you can combine with it to create a proper functional image uploader, for example you can take a look at Ajax and PHP based image uploader here. The first thing you need to do is create a HTML form page, where a file input field should be included within the FORM tag. For example:HTML
- 1
- 2
- 3
- 4
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="image_file" />
<input type="submit" value="Send Image" />
</form>
PHP
- 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
if(isset($_FILES['image_file']))
{
$max_size = 500; //max image size in Pixels
$destination_folder = '/root/path/to/image/files';
$image_name = $_FILES['image_file']['name']; //file name
$image_size = $_FILES['image_file']['size']; //file size
$image_temp = $_FILES['image_file']['tmp_name']; //file temp
$image_type = $_FILES['image_file']['type']; //file type
switch(strtolower($image_type)) //determine uploaded image type
{
//Create new image from file
case 'image/png':
$image_resource = imagecreatefrompng($image_temp);
break;
case 'image/gif':
$image_resource = imagecreatefromgif($image_temp);
break;
case 'image/jpeg': case 'image/pjpeg':
$image_resource = imagecreatefromjpeg($image_temp);
break;
default:
$image_resource = false;
}
if($image_resource){
//Copy and resize part of an image with resampling
list($img_width, $img_height) = getimagesize($image_temp);
//Construct a proportional size of new image
$image_scale = min($max_size / $img_width, $max_size / $img_height);
$new_image_width = ceil($image_scale * $img_width);
$new_image_height = ceil($image_scale * $img_height);
$new_canvas = imagecreatetruecolor($new_image_width , $new_image_height);
//resize image with new height and width
if(imagecopyresampled($new_canvas, $image_resource ,0, 0, 0, 0, $new_image_width, $new_image_height, $img_width, $img_height))
{
if(!is_dir($destination_folder)){ //create dir if it doesn't exist
echo (mkdir($destination_folder))?'New folder Created':'Could create new folder';
}
//Save as jpeg image file
switch(strtolower($image_type))
{
case 'image/png':
imagepng($new_canvas, $destination_folder.'/'.$image_name);
break;
case 'image/gif':
imagegif($new_canvas, $destination_folder.'/'.$image_name);
break;
case 'image/jpeg': case 'image/pjpeg':
imagejpeg($new_canvas, $destination_folder.'/'.$image_name, 80);
break;
}
}
}
}