phpのGDで画像のサイズを変更させる処理をさせていたらエラーが発生!

Fatal error: Allowed memory size of 25165824 bytes exhausted (tried to allocate 12800 bytes)
ってエラーに悩まされました。サーバーのメモリーが足りない感じガーン

3000px とか大きいサイズの写真を使うとエラーがでるみたい。
解決策としては、phpで ini_set('memory_limit', '512M'); って書けばOKでした。
ini_set('memory_limit', '-1'); にすると制限なしになるがキケンなあせる感じ

他の回避方法としては、PHP で大きいJPEGやPNGファイルをPHPで扱うときのメモリエラー回避方法に載ってました。

function setMemoryForImage( $filename ){
$imageInfo = getimagesize($filename);
$MB = 1048576; // number of bytes in 1M
$K64 = 65536; // number of bytes in 64K
$TWEAKFACTOR = 1.5; // Or whatever works for you
$memoryNeeded = round( ( $imageInfo[0] * $imageInfo[1]
* $imageInfo['bits']
* $imageInfo['channels'] / 8
+ $K64
) * $TWEAKFACTOR
);
//ini_get('memory_limit') only works if compiled with "--enable-memory-limit" also
//Default memory limit is 8MB so well stick with that.
//To find out what yours is, view your php.ini file.
$memoryLimit = 8 * $MB;

if (function_exists('memory_get_usage') &&
memory_get_usage() + $memoryNeeded > $memoryLimit)
{
$newLimit = $memoryLimitMB + ceil( ( memory_get_usage()
+ $memoryNeeded
- $memoryLimit
) / $MB
);
ini_set( 'memory_limit', $newLimit . 'M' );
return true;
}else
return false;
}
}