我目前正在爲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);
}
你有沒有找到解決這個問題的辦法?我在Prestashop模塊中遇到了同樣的問題 – Matt 2016-09-02 17:17:49
我不記得我們是如何解決這個問題的。我們很可能採取了不同的方法。 – Martijn 2016-09-03 18:30:13