i try to convert an image png in jpg in a custom module with Magento. The upload works but when i try to convert the pic there is a prblm. There isn't method to convert in the Varien_file_uploader but in the Varien_image there is. I try that :
$uploader = new Varien_File_Uploader('image');
$uploader->setAllowedExtensions(array('jpg','png','gif','jpeg'));
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$uploader->save($path, $_FILES['image']['name']);
$image = new Varien_Image($path . DS . $_FILES['image']['name']);
$image->convert('jpeg');
$image->save($path, 'mypic.jpeg');
Any ideas ? Thx
I created a function, you can use it as helper. If someone need it :)
class YourCompany_YourModule_Helper_Image_Data extends Mage_Core_Helper_Abstract{
public function convert($ext, $path, $name, $newname = NULL)
{
$exploded = explode('.',$name);
$extoriginal = $exploded[count($exploded) - 1];
switch($extoriginal)
{
case 'jpg':
case 'jpeg':
$image = imagecreatefromjpeg($path . $name);
break;
case 'png':
$image = imagecreatefrompng($path . $name);
break;
case 'gif':
$image = imagecreatefromgif($path . $name);
break;
case 'bmp':
$image = imagecreatefrombmp($path . $name);
break;
}
$bg = imagecreatetruecolor(imagesx($image), imagesy($image));
imagefill($bg, 0, 0, imagecolorallocate($bg, 255, 255, 255));
imagealphablending($bg, TRUE);
imagecopy($bg, $image, 0, 0, 0, 0, imagesx($image), imagesy($image));
imagedestroy($image);
$quality = 100;
$newname = ($newname == NULL) ? $exploded[0] : $newname;
switch($ext)
{
case 'jpg':
case 'jpeg':
$newimage = $path . $newname . ".jpg";
imagejpeg($bg, $newimage, $quality);
break;
case 'png':
$newimage = $path . $newname . ".png";
imagepng($bg, $newimage, $quality);
break;
case 'gif':
$newimage = $path . $newname . ".gif";
imagegif($bg, $newimage, $quality);
break;
case 'bmp':
$newimage = $path . $newname . ".bmp";
imagewbmp($bg, $newimage, $quality);
break;
}
imagedestroy($bg);
return $newimage;
}
}
In the config.xml (of your custom module) add this in the global node
<helpers>
<news>
<class>YourCompany_YourModule_Helper_Image</class>
</news>
</helpers>
And to use
$helper = Mage::helper('YourModule');
$helper->convert('jpg', $path, $yourimage);
Enjoy :)
there is not idea for magento function but following is php function that will convert a PNG to JPG with the transparency in white.
$image = imagecreatefrompng($filePath);
$bg = imagecreatetruecolor(imagesx($image), imagesy($image));
imagefill($bg, 0, 0, imagecolorallocate($bg, 255, 255, 255));
imagealphablending($bg, TRUE);
imagecopy($bg, $image, 0, 0, 0, 0, imagesx($image), imagesy($image));
imagedestroy($image);
$quality = 50; // 0 = worst / smaller file, 100 = better / bigger file
imagejpeg($bg, $filePath . ".jpg", $quality);
imagedestroy($bg);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.