Image resize while uploading in PHP with MYSQL database


Images play important role in a website. You can upload and display a lot of images on your website page. This can be cool but if the image size (Height and width) is greater than the page size then it will take time to upload and display. The space will be full of a lot of images because of the extra size. This is not a good idea that you upload any size image on your website. In this tutorial, we will resize the image while uploading using PHP and the MYSQL database. Images will resize during uploading. For example – The user has an image size of 1280X720 and we want to resize this image from 1280X720 to 600X300 then we will create PHP scripts that will help to resize the image and move it o the folder.

Resize image while uploading using PHP with MYSQL database –

As you know that if we resize an image, the image size also decreases like 1MB image will be 500 KB image after resizing.

We will create an HTML form that will help you to upload the image. The image will be resized and moved to the folder. In the HTML form, we will create three other fields  Title, image height image width.

You can set image height and width using the simple HTML form. We will display images and download them with a download button. We will create a download button to download the image after resizing.

First of all, create a MYSQL database table-

CREATE TABLE `items` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `image` varchar(255) DEFAULT NULL,
  `title` varchar(255) DEFAULT NULL,
    PRIMARY KEY (`id`)
) 

Create a database table using the query above. In this table, we will save all images' names with extensions one by one.  All resized image names will be saved in this table. The title is an extra field with an image.

Now we create a connection file. The connection file helps to create a connection between the HTML page and the Mysql database using PHP.

config.php

<?php
$dbHost = 'localhost';
$dbName = 'tute';
$dbUsername = 'root';
$dbPassword = '';
$db= mysqli_connect($dbHost, $dbUsername, $dbPassword, $dbName); 
?>

Now create an index.php file. In the index file, we will display all resized images in the HTML table with image preview, image size, title, and download button. The image upload button will be here. We will create an image upload file after the index file. 

index.php

<?php require_once("config.php");
include("functions.php"); 
?>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title></title>
	<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="container_display">
	<span style="float:right;"><a href="upload.php"><button class="btn-primary">Upload New image </button></a></span>
	<br>
	<?php 
	if(isset($_GET['status']))
		{
    $status=$_GET['status'];
	if($status=='success')
	{
		echo '<div class="success">Image resized and uploaded successfully.. </div>'; 
	}
}
?>
	<table cellpadding="10">
		<tr>
			<th> Image</th>
			<th>Title</th>
			<th>Size </th>
			<th>Action </th>
		</tr>
		<?php $res=mysqli_query($db,"SELECT* from items ORDER by id DESC");
			while($row=mysqli_fetch_array($res)) 
			{
			echo '<tr> 
            <td><img src="uploads/'.$row['image'].'" height="200"></td> 
             <td>'.$row['title'].'</td> 
            <td><strong>'.image_size('uploads/'.$row['image']).'</strong></td> 
          <td><a href="download.php?id='.$row['id'].'"><button class="btn-primary download_btn">Download</button></a>
				</tr>';

} ?>	
	</table>
	</div>
</body>
</html>

Create a CSS file style.css to design the form and index page. 

style.css

body{
background-color: #f1f1f1;
	}
		.form-control {
    width: 100%;
    height: 25px;
    padding: 6px 12px;
    font-size: 14px;
    color: #555;
    background-color: #fff;
    border: 1px solid #ccc;
    border-radius: 4px;
}
.btn-primary {
    padding: 6px 12px;
    font-size: 14px;
    font-weight: 400;
    cursor: pointer;
    border: 1px solid transparent;
    border-radius: 4px; 
    background-color: #337ab7;
    color: #fff;
}
.download_btn{
    background: #479920 !important;
}
.container 
{ 
margin-left: 30%;
width: 450px ;
background-color: #fff;
padding: 10px;
padding-right: 40px;
    border: 1px solid #ccc;
    border-radius: 4px;
 }
 .container_display
{ 
margin-left: 10%;
width: 900px ;
background-color: #fff;
padding: 10px;
padding-right: 40px;
    border: 1px solid #ccc;
    border-radius: 4px;
 }

label   {
	font-size: 16px;
}
.success 
{ 
	margin: 5px auto;
  border-radius: 5px;
  border: 3px solid #fff;
  background: #33CC00;
  color: #fff;
font-size: 20px;
  padding: 10px;
  box-shadow: 10px 5px 5px grey;
}

Upload image and display in PHP

Image upload and resize in PHP 

Now, we will create an upload form. The form will help you to upload images and resize them. The image will move to the folder after resizing and the image name with extension will insert into the MYSQL database table.

First of all, create a folder uploads

Create a NEW folder uploads

All images after resizing will be moved to this folder.

Now create an upload.php file.

upload.php

<?php require_once("config.php");
	include("functions.php"); 
?>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="style.css">
	<title>Resize image while uploading in PHP</title>
</head>
<body>
	<?php
		if(isset($_POST['form_submit']))
		{	
			$title=$_POST['title'];
			$desiredHeight =$_POST['height'];
		$desiredWidth=$_POST['width'];
$folder = "uploads/";
$image_file=$_FILES['image']['name'];
 $file = $_FILES['image']['tmp_name'];
 $path = $folder . $image_file;  
 $target_file=$folder.basename($image_file);
 $imageFileType=pathinfo($target_file,PATHINFO_EXTENSION);
//Allow only JPG, JPEG, PNG & GIF etc formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
 $error[] = 'Sorry, only JPG, JPEG, PNG & GIF files are allowed';   
}
//Set image upload size 
    if ($_FILES["image"]["size"] > 1000000) {
   $error[] = 'Sorry, your image is too large. Upload less than 1 MB in size.';
}
if(!isset($error))
{
$imageProcess = 0;
if(is_array($_FILES)) {
$sourceProperties = getimagesize($file);
 $unique_id=mt_rand(1000,9999).time(); 
$uploadImageType = $sourceProperties[2];
$sourceImageWidth = $sourceProperties[0];
$sourceImageHeight = $sourceProperties[1];
$image_point = $folder."image_".$unique_id.'.'. $imageFileType; 
switch ($uploadImageType) {
case IMAGETYPE_JPEG:
$resourceType = imagecreatefromjpeg($file); 
$imageLayer = resizeImage($resourceType,$sourceImageWidth,$sourceImageHeight,$desiredWidth,$desiredHeight);
imagejpeg($imageLayer,$image_point);
break;
case IMAGETYPE_GIF:
$resourceType = imagecreatefromgif($file); 
$imageLayer = resizeImage($resourceType,$sourceImageWidth,$sourceImageHeight,$desiredWidth,$desiredHeight);
imagegif($imageLayer,$image_point);
break;
case IMAGETYPE_PNG:
$resourceType = imagecreatefrompng($file); 
$imageLayer = resizeImage($resourceType,$sourceImageWidth,$sourceImageHeight,$desiredWidth,$desiredHeight);
imagepng($imageLayer,$image_point);
break;
default:
$imageProcess = 0;
break;
}
move_uploaded_file($file,$folder. $unique_id. ".". $imageFileType);
unlink($folder.$unique_id.'.'.$imageFileType); 
$imgtodb='image_'.$unique_id.'.'.$imageFileType; 
$imageProcess = 1;
}
$result=mysqli_query($db,"INSERT INTO items(image,title) VALUES('$imgtodb','$title')"); 
if($result)
{
	header("location:index.php?status=success");
}
else 
{
	echo 'Something went wrong'; 
}
}
		}
if(isset($error)){ 

foreach ($error as $error) { 
	echo '<div class="message">'.$error.'</div><br>'; 	
}
}
	?> 
	<div class="container">
		<h1>Resize image while uploading </h1>
	<?php if(isset($image_success))
		{
		echo '<div class="success">Image Uploaded successfully</div>'; 
		} ?>
<form action="" method="POST" enctype="multipart/form-data">
	<label>Image </label>
	<input type="file" name="image" class="form-control" required/>
	<br><br>
	<label>Title</label>
	<input type="text" name="title" class="form-control">
	<br><br>
	<label>Height</label>
	<input type="number" name="height" class="form-control">
	<br><br>
		<label>Width </label>
	<input type="number" name="width" class="form-control">
	<br><br>
		
	<button name="form_submit" class="btn-primary"> Upload</button>
</form>
</div>
</body>
</html>

You will need an image_size() user-defined function to resize image .

Resize image while uploading in PHP and MYSQL

Now, create a file functions.php.

functions.php 

<?php 
function image_size($image)
{
	$data = getimagesize($image);
$width = $data[0];
$height = $data[1]; 
$size=$width.'X'.$height; 
return $size; 
}
function resizeImage($resourceType,$image_width,$image_height,$desiredWidth,$desiredHeight) {
$imageLayer = imagecreatetruecolor($desiredWidth,$desiredHeight);
imagecopyresampled($imageLayer,$resourceType,0,0,0,0,$desiredWidth,$desiredHeight, $image_width,$image_height);
return $imageLayer;
}
?> 

We already included functions.php in the upload file. In the functions file , we created image_size() user-defined function and used resizeImage() readymade function of PHP. The resizeImage() function is used to scale an image to the desired dimensions. It takes many parameters to resize image.

Like-

resizeImage($resourceType,$image_width,$image_height,$desiredWidth,$desiredHeight);

In the upload.php file, we created an HTML form. The HTML form contains many fields like – The browse file box (input type file), an extra Field title, and image height, width.

We used imagecreatefromjpeg(),imagecreatefromgif() and imagecreatefrompng()  inbuilt functions  to create a new image from file or URL with switch case .

You can set height and width in function.php without giving in the form.

When a user uploads an image, the image resizes using the resizeImage() function and moves to the folder and the image name with extension is saved into the database. We fetch and display images using the MYSQL database and folder name.

Now, create a download.php file.

The download file will be used to download the image after being resized from the uploads folder.

download.php

<?php require_once("config.php");
$id = $_GET['id'];
$stmt=mysqli_query($db,"SELECT image from items WHERE id=$id");
$count=mysqli_num_rows($stmt);
if($count==1) {
    $row=mysqli_fetch_array($stmt);
     $image=$row['image'];
$file='uploads/'.$image;
if (headers_sent()) {
    echo 'HTTP header already sent';
} else {
        ob_end_clean();
        header("Content-Type: application/image");
        header("Content-Disposition: attachment; filename=\"".basename($file)."\"");
        readfile($file);
        exit;
}
echo "<script>window.close();</script>";
}
else 
{
    echo 'File not found '; 
} 

?>

In this way, you can upload the image and resize them using PHP and MYSQL database


Please Share

Recommended Posts:-

Previous Posts:-

Featured Items:-


Modern blog CMS in PHP with MYSQL database | PHP blog scripts

$67



Paypal payment form with email, invoice generator in PHP website | Scripts

$39



Certificate system in PHP website | PHP scripts

$22





11 Comments
osariemen osamwonyi 30 Apr 2023

I dont know what to do ------> Fatal error: Uncaught Error: Call to undefined function imagecreatefromjpeg() in upload.php on line 46

@osariemen osamwonyi replied by Techno Smarter 30 Apr 2023

Which PHP version are you using?

AYO CELESTINE 08 Oct 2022

Thank you so much for this awesome helpful code, but how can i allow users to upload images more than 1MB?

@AYO CELESTINE replied by Techno Smarter 08 Oct 2022

You can restrict the user to upload image sizes less than 1 MB.

if ($_FILES["image"]["size"] > 1000000) {
$error[] = 'Sorry, your image is too large. Upload less than 1 MB in size.';
}

1MB == 1048576 bytes.You can increase the size according to your need. like

 2 MB = 2000000 bytes

@Techno Smarter replied by AYO CELESTINE 08 Oct 2022

Wow you are extremely helpful.God bless you. I will try it, 6MB will be = 6000000 bytes.

@AYO CELESTINE replied by Techno Smarter 08 Oct 2022

Yes, try it and for your kind information you can search on Google like this 

https://www.google.com/search?q=6+MB+in+bytes

You can get all number bytes like this.

@Techno Smarter replied by Ayo Celestine 08 Oct 2022

In my database i set my Data Type to longblob and sent my upload limit to 9000000. If i upload image like 4MB, the file data will be submitted to the database but the image wont be uploaded. Am i doing anything wrong?

@Ayo Celestine replied by Techno Smarter 08 Oct 2022

Did you create an uploads folder?

$folder = "uploads/";

You have to create a folder name "uploads" and Create an image column with varchar data type in the table. Check the table query above. We are creating an image varchar column, not longblob. Only image names with extensions will be saved in the database table, not as a blob. The image will be moved to the uploads folder.

or basic upload operation, check this tutorial. How to upload image and display in PHP?

@Techno Smarter replied by Ayo Celestine 08 Oct 2022

Yes , It works if i upload images ,less than 1MB it uploads fine and submits data to the database. 

@Ayo Celestine replied by Techno Smarter 08 Oct 2022

If it's working then you can increase the image size by changing bytes. It will work on that limited size.

4MB, 6 MB, or 9MB images can take more time. Use an updated local server or Try to increase upload_max_filesize. 

@Techno Smarter replied by Ayo Celestine 09 Oct 2022

Thanks very much, its working now. I have increased the Maximum allowed size for files upload. upload_max_filesize = 20M .Really appreciate your kindness.