Magento: Resize image

The original path is: path/to/magento/media/blog/<imagename>
The path of the resized image is: path/to/magento/media/blog/resized/<imagename>

public function resizeImg($fileName, $width, $height = null)
{

	$folderURL = Mage::getBaseDir(Mage_Core_Model_Store::URL_TYPE_MEDIA). DS .'blog'. DS;
	$basePath = $folderURL . $fileName;
	$newPath = $folderURL. 'resized' . DS . $fileName;
	$resizedURL = Mage::getBaseUrl('media') . 'blog' . DS . $fileName;;

	//if width empty then return original size image's URL
	if ($width != '') {
		//if image has already resized then just return URL
		if (file_exists($basePath) && is_file($basePath) && !file_exists($newPath)) {
			$imageObj = new Varien_Image($basePath);
			$imageObj->constrainOnly(TRUE);
			$imageObj->keepAspectRatio(FALSE);
			$imageObj->keepFrame(FALSE);
			$imageObj->resize($width, $height);
			$imageObj->save($newPath);
		}
		$resizedURL = Mage::getBaseUrl('media') . 'blog' . DS . "resized" . DS . $fileName;
	}
	return $resizedURL;
}

Sven Wappler

Webentwickler, TYPO3ler, Hobby-Fotograf

Das könnte Dich auch interessieren...

1 Antwort

  1. Matthias sagt:

    Thank you! Very nice function 😉

    You should add: $imageObj->keepTransparency(true);

    Otherwise, transparent images will get a black background.

Schreibe einen Kommentar