Reputation: 1654
I am trying to upload an image via PHP. On upload, it should become resized that its' dimensions are as big as I defined it in my config[]-array and that its' filesize is also smaller or equal to the predefined value in my config[]-array. But somehow, the method getFileSize() always returns the same size, even after resizing the image.
Here's my code. Explanation follows.
$tries = 0;
while ( $image->getFileSize() > $config['image_max_file_size'] && $tries < 10 ) {
$factor = 1 - (0.1 * $tries);
echo $image->getFileSize().PHP_EOL;
if ( !$image->resize($config['image_max_width'], $config['image_max_height'], $factor) ) {
return false;
}
$tries++;
}
$image is an object of the type Picture, which is just a wrapper-class for all kind of functions I need related to modifying pictures.
$config is my configuration-array which includes all kind of predefined values.
$tries holds the number of tries that are allowed. The program is allowed to resize the image no more than 10 times.
getFileSize() returns the image-filesize via return filesize(path)
resize(maxWidth,maxHeight,factor) resizes the image to the size mentioned in the parameters. After it resized the picture, it saves the result to the same path, the filesize is read from.
I'll just post the resize() and getFileSize() method, since it may interest you:
function resize($neededwidth, $neededheight, $factor) {
$oldwidth = $this->getWidth($this->file_path);
$oldheight = $this->getHeight($this->file_path);
$neededwidth = $neededwidth * $factor;
$neededheight = $neededheight * $factor;
$fext = $this->getInnerExtension();
$img = null;
if ($fext == ".jpeg" ) {
$img = imagecreatefromjpeg($this->file_path);
} elseif ($fext == ".png") {
$img = imagecreatefrompng($this->file_path);
} elseif ($fext == ".gif") {
$img = imagecreatefromgif($this->file_path);
} else {
return false;
}
$newwidth = 0;
$newheight = 0;
if ($oldwidth > $oldheight && $oldwidth > $neededwidth) { // Landscape Picture
$newwidth = $neededwidth;
$newheight = ($oldheight / $oldwidth) * $newwidth;
} elseif ($oldwidth < $oldheight && $oldheight > $neededheight) { // Portrait Picture
$newheight = $neededheight;
$newwidth = ($oldwidth / $oldheight) * $newheight;
}
$finalimg = imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($finalimg, $img, 0, 0, 0, 0, $newwidth, $newheight, $oldwidth, $oldheight);
if ($fext == ".jpeg" ) {
if ( !imagejpeg($finalimg, $this->file_path, 100) ) return false;
} elseif ($fext == ".png") {
if ( !imagepng($finalimg, $this->file_path, 9) ) return false;
} elseif ($fext == ".gif") {
if ( !imagegif($finalimg, $this->file_path) ) return false;
} else {
return false;
}
imagedestroy($img);
return true;
}
getFileSize()
function getFileSize() {
return filesize($this->file_path);
}
Thanks!
Upvotes: 2
Views: 1458
Reputation: 121
Try http://www.php.net/manual/en/function.clearstatcache.php
function getFileSize() {
clearstatcache();
return filesize($this->file_path);
}
Upvotes: 9