Hello Stackoverflowers,
I have successfully been able to compress the main uploaded image, but I don't know how to use the same function to compress the thumbnail.
The code main purpose is as follows:
1- Upload an image
2- Rename
3- Compress
4- Create thumbnail
5- Compress the thumbnail
My issue it with number 5, I don't know how to compress the thumbnail.
Below are my php and HTML code:
if (isset($_POST["submit"])) {
if (is_array($_FILES)) {
if ($_FILES['image']['size'] <= 5000000) {
$file = $_FILES['image']['tmp_name'];
$sourceProperties = getimagesize($file);
$fileNewName = "[" . "999" . "]-" . time();
$folderPath = "uploads/";
$ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
$imageType = $sourceProperties[2];
$data = getimagesize($file);
$width = $data[0];
$height = $data[1];
switch ($imageType) {
case IMAGETYPE_PNG:
$imageResourceId = imagecreatefrompng($file);
$targetLayer = imageResize($imageResourceId, $sourceProperties[0], $sourceProperties[1]);
imagepng($targetLayer, $folderPath . $fileNewName . "_thump." . $ext);
break;
case IMAGETYPE_GIF:
$imageResourceId = imagecreatefromgif($file);
$targetLayer = imageResize($imageResourceId, $sourceProperties[0], $sourceProperties[1]);
imagegif($targetLayer, $folderPath . $fileNewName . "_thump." . $ext);
break;
case IMAGETYPE_JPEG:
$imageResourceId = imagecreatefromjpeg($file);
$targetLayer = imageResize($imageResourceId, $sourceProperties[0], $sourceProperties[1]);
imagejpeg($targetLayer, $folderPath . $fileNewName . "_thump." . $ext);
break;
default:
echo "Invalid Image type.";
exit;
break;
}
compressImage($file, $folderPath . $fileNewName . "." . $ext, 60);
echo "Image Resize Successfully.";
} else {
echo "too big!";
}
}
}
// Compress image
function compressImage($source, $destination, $quality)
{
$info = getimagesize($source);
if ($info['mime'] == 'image/jpeg')
$image = imagecreatefromjpeg($source);
elseif ($info['mime'] == 'image/gif')
$image = imagecreatefromgif($source);
elseif ($info['mime'] == 'image/png')
$image = imagecreatefrompng($source);
imagejpeg($image, $destination, $quality);
}
function imageResize($imageResourceId, $width, $height)
{
$targetWidth = (20 / 100) * $width;
$targetHeight = (20 / 100) * $height;
echo $targetWidth . " x " . $targetHeight . " <br> ($width x $height)";
$targetLayer = imagecreatetruecolor($targetWidth, $targetHeight);
imagecopyresampled($targetLayer, $imageResourceId, 0, 0, 0, 0, $targetWidth, $targetHeight, $width, $height);
return $targetLayer;
}
HTML
<div class="container">
<form method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit" name="submit" value="Submit" />
</form>
</div>
<br><br>
<a href="index-2.php">Reload Page</a>
Please forgive my silly question as I believe it is a very simple question, but I just started developing using php, just few months ago.
Thank you in advance and I really appreciate your help.