halocursed halocursed - 2 months ago 11
PHP Question

compress image file size on upload?

I am uploading product screenshots to my website... I want to upload the original image as it is and also create a thumbnail for it, but after uploading both the files the filesize of the thumbnail created is a bit larger than expected. Is there any way I could reduce the filesize of the thumbnail without compromising much on the quality in php or by using Imagemagick( which I have no idea how to use but I'm willing to learn if needed)...

Below is the code I'm using to upload my files..


<form action="<?php echo $_server['php-self']; ?>" method="post" enctype="multipart/form-data" id="something" class="uniForm">
<input name="new_image" id="new_image" size="30" type="file" class="fileUpload" />
<button name="submit" type="submit" class="submitButton">Upload/Resize Image</button>







<?php
if(isset($_POST['submit'])){
if (isset ($_FILES['new_image'])){
$imagename = $_FILES['new_image']['name'];
$source = $_FILES['new_image']['tmp_name'];
$target = "images/".$imagename;
move_uploaded_file($source, $target);

$imagepath = $imagename;
$save = "images/" . $imagepath; //This is the new file you saving
$file = "images/" . $imagepath; //This is the original file

list($width, $height) = getimagesize($file) ;


$tn = imagecreatetruecolor($width, $height) ;
$image = imagecreatefromjpeg($file) ;
imagecopyresampled($tn, $image, 0, 0, 0, 0, $width, $height, $width, $height) ;

imagejpeg($tn, $save, 100) ;

$save = "images/sml_" . $imagepath; //This is the new file you saving
$file = "images/" . $imagepath; //This is the original file

list($width, $height) = getimagesize($file) ;

$modwidth = 130;

$diff = $width / $modwidth;

$modheight = 185;
$tn = imagecreatetruecolor($modwidth, $modheight) ;
$image = imagecreatefromjpeg($file) ;
imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ;

imagejpeg($tn, $save, 100) ;
echo "Large image: <img src='images/".$imagepath."'><br>";
echo "Thumbnail: <img src='images/sml_".$imagepath."'>";

}
} ?>


Kindly point me in the right direction...Thanks

Answer

Don't pass 100 as the quality for imagejpeg() - anything over 90 is generally overkill and just gets you a bigger JPEG. For a thumbnail, try 75 and work downwards until the quality/size tradeoff is acceptable.

//try this
imagejpeg($tn, $save, 75) ;