Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Optimizing images - like in fireworks... 1

Status
Not open for further replies.

Haraldo

Programmer
Jun 9, 2003
41
GB
Is there anyway i can reduce the quality of my images automatically in php. I need to reduce the quality to 80% or so, to reduce the file size.

I need to introduce the script when the image is uploaded to the site. Since i can't guarantee whether the client has uploaded an optimized image i could check to see if the file is in a range of sizes and if outside, optimize the image. I can't see a function in PHP that will optimize and reduce quality.

If anyone has any ideas and/or solutions, i would be greatful to hear from you,

Thanks,
 
This is a clipping of code I am using on one of my web applications (I hope I have included all the variables and parts) - it's called as part of a file upload:
Code:
$TEMP_dir = '../../assets/images/products';
$extension = pathinfo($_FILES['upload_img']['name']);
$extension = $extension[extension];
if ($extension == 'jpg') {
	list($width, $height) = getimagesize($_FILES['upload_img']['tmp_name']);
	$image_temp = imagecreatetruecolor($width, $height);
	$image = imagecreatefromjpeg($_FILES['upload_img']['tmp_name']);
	imagecopyresampled($image_temp, $image, 0, 0, 0, 0, $width, $height, $width, $height);
	imagejpeg($image_temp, $TEMP_dir.'/'.$_FILES['upload_img']['name'],100);
} else {
	move_uploaded_file($_FILES['upload_img']['tmp_name'],$TEMP_dir.'/'.$_FILES['upload_img']['name']);
}
This code is a standard upload, with the addition of some optimisation code that you may also want to use. Basically I am making a new canvas and then copying the old JPG into the new one... the side effect being it strips out all themeta data (which I found to be a significant percentage for smaller images). I resample my JPG at 100% to do this. You could easily change this number for optimal results. Change the following line:
Code:
imagejpeg($image_temp, $TEMP_dir.'/'.$_FILES['upload_img']['name'],[b]100[/b]);
I've used 100 (= 100%) and you could change that to 80 (= 80%).

Apologies if my code isn't as clean as it could be... hopefully you can see how I did it anyway.

Cheers,
Jeff

[tt]Jeff's Page [/tt][tt]@[/tt][tt] Code Couch
[/tt]

What is Javascript? faq216-6094
 
Jeff,

Your a genius!

Thanks, i have pretty much the same code as above apart form the creation of a new canvas. Thats some really good info you gave me. I didn't consider at all the meta stuff. Thanks for the time and effort of your post.

Chears,
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top