MYBB avatars image optimization script task?
#1
Can anybody help me to get started with this?

I would like to create a PHP script to optimize images in avatars folder and then create task to run the script once X days.
Only optimize images that were not already optimized?

Found this code!


<?php
 $dir = '/home/some_directory/'; // the directory with your files
 $compr = 80; // the quality precentage
 
 if ($handle = opendir($dir)) {
   while (false !== ($file = readdir($handle))) {
     $path = $dir.$file;
     if (is_file($path)) {
       $ext = pathinfo($path, PATHINFO_EXTENSION);
       if (preg_match('/^(jpg|jpeg)$/i', $ext)) {
       exec(sprintf('convert %s -quality %d %s', $path, $compr, $path));
    }
  }
 }
 closedir($handle);
}
?>
Reply
#2
Maybe I won't immediately answer your question because :
1. You can specify in AdminCP the maximum weight (in KB) that a user is allowed to use when uploading their avatar.
2. Avatars are never an issue at all, they weigh 10kb at most usually.
3. The script you are showing don't "optimize", it just lowers the quality of avatars, which would make them look blurred and glittery.
4. I'd rather advice you not to use exec() function, you would then have to know what command lines your OS is capable of using, and can cause unwanted behavior. Plus :

You should probably replace :
$path = $dir.$file;

By :
$path = $dir.escapeshellarg($file);

As the filename is coming from the user, and I doubt MyBB dev's have escaped it for shell uses.


Now if you still want to "optimize" the way you showed in OP, you'd need some kind of database/file storage/caching system to remember what images have been already "optimized".

Last but not least, never "blindly" copy/paste pieces of code found in internet Wink

Oh I would add one thing, are you planning on using that in a plugin that you'd publish here? Don't bother, they won't approve it as :

1. It would break transportability, because people won't be able to deploy your plugin on non-*Nix systems.
2. Hosts, even the most sophisticated ones usually disable using exec() function.
Rasmus Lerdorf Wrote:If eval() is the answer, you're almost certainly asking the wrong question. - Rasmus Lerdorf
Reply
#3
Thanks buddy very much! Any idea how to make this code work with:
jpg
png
gif

image extensions. I am looking to grab the image reduce it's size and then replace original image with new one?
Reply
#4
Replace
       if (preg_match('/^(jpg|jpeg)$/i', $ext)) {

By
       if (preg_match('/^(jpg|jpeg|png|gif)$/i', $ext)) {

would allow the script to be executed for such extensions.
Rasmus Lerdorf Wrote:If eval() is the answer, you're almost certainly asking the wrong question. - Rasmus Lerdorf
Reply
#5
Thanks so much I am having issues with Insights have to act now can't wait sorry!

Please one more question?

What this means "PATHINFO_EXTENSION" in the code below?

$ext = pathinfo($path, PATHINFO_EXTENSION);
Reply
#6
That gets the extension of the file...
Reply
#7
What should I put there?
Reply
#8
Unless you resize the image or greatly reduce the pixel count (quality) most of the time the automated processes tend to make the image filesize larger.

I have tried both GD and ImageMagick, for GIF, BMP, JPG and PNG files. All get larger without significant changes to dimensions or pixel count. Then you have to deal with animated GIFs.

its not worth it for avatars.
Lost interest, sold my sites, will browse here once in a while. It's been fun.
Reply
#9
Thanks guys I guess have to do it manually. Maybe for websites that have good rankings and traffic it's not important but I need to optimize my site and Insights tells me to optimize avatars, gotta have do it need this extra score!

<?php
chdir( 'images1' );
//using backticks to run system command
mogrify -quality 10 *.jpg;
?>

How to make this work???

Which file is responsible for image optimizations during upload?????
Reply
#10
Hey again,

Wow you seem very lost, but let's get there one step at a time, first of all in PHP, this doesn't work,
*quoting your post*

(2014-08-28, 03:31 PM)marcus123 Wrote: <?php



chdir( 'images1' );
//using backticks to run system command
`mogrify -quality 10 *.jpg`;
?>

You can only use exec(), system() or such functions to run command lines, as you could see in the code you've posted in the OP.

Now I've done some research for an "image compression script in PHP", and came across this one :
http://zenverse.net/php-reducing-image-f...-using-gd/

function compress_image($source_url, $destination_url, $quality) {
	$info = getimagesize($source_url);
 
	if ($info['mime'] == 'image/jpeg') $image = imagecreatefromjpeg($source_url);
	elseif ($info['mime'] == 'image/gif') $image = imagecreatefromgif($source_url);
	elseif ($info['mime'] == 'image/png') $image = imagecreatefrompng($source_url);
 
	//save file
	imagejpeg($image, $destination_url, $quality);
 
	//return destination file
	return $destination_url;
}
 
//usage
$compressed = compress_image('source.png', 'destination.jpg', 90);

Now, as you may see, the function compress_image(), would compress the image 'source.png' at a quality of 90%, and save it as 'destination.jpg'.

Note:
- Third parameter, 90, means you reduce the quality by 10%, so if you want a very very bad image, lower this to 50 or even less.

Now you need to iterate over your avatars directory, and compress each image, so the full code would be something like :


<?php

$avatars_dir = "/var/www/mybb_forum_path/uploads/avatars/"; // the full path to your avatars directory
$quality = 80;


$converted_files = @unserialize(file_get_contents("./converted_files.txt"));
// first time? create the array
$converted_files = is_array($converted_files) ? $converted_files : array();


foreach(glob($avatars_dir . "*.*") as $image) {
	if(in_array($image, $converted_files)) {
		continue;
	}
    $ext = pathinfo($image, PATHINFO_EXTENSION);
    if(preg_match('/^(jpg|jpeg|gif|png)$/i', $ext)) {
		$converted = compress_image($image, $image, $quality);
		$converted_files[] = $converted;
        echo "Successfully converted : <b>" . $converted . "</b><br>";
    }
}

function compress_image($source_url, $destination_url, $quality) {
	$info = getimagesize($source_url);
 
	if ($info['mime'] == 'image/jpeg') $image = imagecreatefromjpeg($source_url);
	elseif ($info['mime'] == 'image/gif') $image = imagecreatefromgif($source_url);
	elseif ($info['mime'] == 'image/png') $image = imagecreatefrompng($source_url);
 
	//save file
	imagejpeg($image, $destination_url, $quality);
 
	//return destination file
	return $destination_url;
}

@file_put_contents("./converted_files.txt", serialize($converted_files));


CHANGE :
$avatars_dir = "/var/www/mybb_forum/uploads/avatars/";
to the avatars directory of your forum!


ALSO :
- Next to the php file you create, also make an empty file named converted_files.txt where this script store the files it converts, so it won't re-convert them on next run Big Grin .

WARRANTY :
This is a 2 minute script, I didn't spend time on it at all, there's no warranty this would work as I only tested it on one scenario of use, also changing the path of your avatars will cause the script to re-convert them all, as it is path-based which I know is bad but whatever Cool .
Also, I used "@" to hide any PHP errors/warnings which I personally hate using, but ehm let's not comment on that either  Sleepy .


I've tested this on a directory containing a JPEG image weighing 523kb, at a 80% quality it got down to 380kb.
Rasmus Lerdorf Wrote:If eval() is the answer, you're almost certainly asking the wrong question. - Rasmus Lerdorf
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)