我目前正在为Prestashop构建一个导入模块。该模块正在导入约3000种产品,需要将每个产品图像调整为5种不同的缩略图格式。问题是:脚本消耗大量内存。我正在谈论100 MB峰值和高达27 MB的过程。我很惭愧地说我对整个记忆管理的东西都不太熟悉,所以欢迎任何帮助!
我使用的代码如下。 resizeImg方法应该是最有趣的,其他方法仅用于说明我如何处理任务。有谁知道为什么我的内存峰值超过100MB?
public function main() {
foreach( $products as $product ) {
self::copyImg( $imageURL );
}
}
static private function copyImg( $imageURL ) {
// Copy image from $imageURL to temp folder
foreach( $imageTypes as $type ) {
self::resizeImg( $tempImage, $destination, $type['width'], $type['height']);
}
}
static private function resizeImg( $sourceFile, $destFile, $destWidth, $destHeight )
{
list( $sourceWidth, $sourceHeight, $type, $attr ) = getimagesize( $sourceFile );
if ( is_null( $destWidth ) ) $destWidth = $sourceWidth;
if ( is_null( $destHeight ) ) $destHeight = $sourceHeight;
$sourceImage = imagecreatefromjpeg( $sourceFile );
$widthDiff = $destWidth / $sourceWidth;
$heightDiff = $destHeight / $sourceHeight;
if ( $widthDiff > 1 && $heightDiff > 1 ) {
$nextWidth = $sourceWidth;
$nextHeight = $sourceHeight;
} else {
if ( Configuration::get( 'PS_IMAGE_GENERATION_METHOD' ) == 2 || ( ! Configuration::get( 'PS_IMAGE_GENERATION_METHOD' ) AND $widthDiff > $heightDiff ) ) {
$nextHeight = $destHeight;
$nextWidth = round( $sourceWidth * $nextHeight / $sourceHeight );
$destWidth = ( ! Configuration::get( 'PS_IMAGE_GENERATION_METHOD' ) ? $destWidth : $nextWidth );
} else {
$nextWidth = $destWidth;
$nextHeight = round( $sourceHeight * $destWidth / $sourceWidth );
$destHeight = ( ! Configuration::get( 'PS_IMAGE_GENERATION_METHOD' ) ? $destHeight : $nextHeight );
}
}
$destImage = imagecreatetruecolor( $destWidth, $destHeight );
$white = imagecolorallocate( $destImage, 255, 255, 255 );
imagefilledrectangle( $destImage, 0, 0, $destWidth, $destHeight, $white );
imagecopyresampled( $destImage, $sourceImage, ( ( $destWidth - $nextWidth ) / 2 ), ( ( $destHeight - $nextHeight ) / 2 ), 0, 0, $nextWidth, $nextHeight, $sourceWidth, $sourceHeight );
imagecolortransparent( $destImage, $white );
imagejpeg( $destImage, $destFile, 90 );
imagedestroy( $sourceImage );
imagedestroy( $destImage );
}
答案 0 :(得分:1)
这些图片有多大?请记住,一旦将它们加载到GD中,它们就会被解压缩为每个像素3(或4)个字节。对于6666x5000左右的图像,24位的100mb就足够了。您是否检查过调整大小计算是否正常工作?如果他们错了,你可能会试图错误地创建一个巨大的'dest'图像。
我也没看到你在哪里写出调整大小的图像。有很多调整大小/复制,但你没有imagejpeg()
或imagepng()
等...写出调整大小的图像。