PHP経由で画像をアップロードしようとしています。アップロード時に、サイズが config[]-array で定義したのと同じ大きさになり、そのファイルサイズも config[]-array の定義済みの値以下になるようにサイズ変更する必要があります。しかし、どういうわけか、メソッド getFileSize() は、画像のサイズを変更した後でも常に同じサイズを返します。
これが私のコードです。説明は次のとおりです。
$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は Picture 型のオブジェクトです。これは、画像の変更に関連して必要なすべての種類の関数の単なるラッパー クラスです。
$configは、すべての種類の事前定義された値を含む構成配列です。
$triesは、許可される試行回数を保持します。プログラムで画像のサイズを変更できるのは 10 回までです。
getFileSize()は return filesize( path )を介して画像ファイルサイズを返します
resize(maxWidth,maxHeight,factor)は、パラメーターで指定されたサイズに画像のサイズを変更します。画像のサイズを変更した後、結果を同じパスに保存し、ファイルサイズを読み取ります。
興味があるかもしれないので、 resize() と getFileSize() メソッドだけを投稿します。
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);
}
ありがとう!