Resizing magento gallery images - magento

i am trying to display product gallery images in my custom cms home page. If i use the code from media.phtml to display the gallery images, it does not work. I found this piece of code and it worked.
<div id="thumbs" class = "thumbs-home">
<?php
$obj = new Mage_Catalog_Block_Product_View_Media();
$_product1 = new Mage_Catalog_Model_Product();
// Load all product information of a particular product
$Products_one = Mage::getModel('catalog/product')->load($productId);
// Use your Product Id instead of $id
$countt = count($Products_one->getMediaGalleryImages());
if($countt>0){
foreach ($Products_one->getMediaGalleryImages() as $_image)
{
// For the Original Image
$thumb_img = "<img src=".Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA).str_replace(Mage::getBaseUrl('media'),"",$_image->url)." alt=''width='60' height='60' />";
echo "<a href='".Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA).str_replace(Mage::getBaseUrl('media'),"",$_image->url)."'rel='lightbox[gallery]'>".$thumb_img."</a>";
//For gallery Image
//$resizeimage = $obj->helper('catalog/image')->init($_product, 'thumbnail', $_image->getFile())->backgroundColor(242,242,243)->resize(400,300);
//echo "<img src=".$resizeimage."alt='' />";
}
}
?>
This gets the actual images and gets resized by the width and height attributes. But i want to resize the image through magento. The last piece of code $resizeimage is not working for some reason. How can i make this work? The problem is that i am using a lightbox to display the gallery images which displays the actual high resolution images that are too large. The light box takes in width and height of image provided and i am not able to figure out as to how i set a standard dimensions for the light box. So the only other option is the have the images resized by magento before passing them to the lightbox. Thanks.

You just need to call proper object, instead of $obj->helper you should use Mage::helper, so your call should look like this:
print Mage::helper('catalog/image')
->init($product, 'thumbnail', $image->getFile())
->backgroundColor(255,255,255)
->resize(100,100);
And that's it! :)

Related

Importing products into Magento breaks images on existing products

After exporting, changing some details and then importing a large number of products into Magento, I noticed all the images are no longer set. The images still exist in the media gallery for each product, but they are not set as the base image.
I've seen that in some cases, you need to copy images over to a /media/import/ folder, but is it possible to change the import file so that I can keep the images where they are?
Right now, all the images appear to be in a folder: /media/catalog/product/
Any help would be very appreciated.
Additionally, if it were possible to run a script that sets all product's base image to the first image in its gallery, that would work just as well. Thanks!
Let's say that you have load the products and you are ready to make a change and save them. With this code:
if (file_exists($imagePath)) {//New image file
//Load your media table
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
try {
//Now you have all the images available for your product
//if you previously have assign anything
$items = $mediaApi->items($product->getId());
//loop them
foreach ($items as $item) {
//With that line you can remove them if you want
echo ($mediaApi->remove($product->getId(), $item['file']));
}
} catch (Exception $exception) {
var_dump($exception);
die('Exception Thrown');
}
$cache = Mage::getSingleton('core/cache');
$cache->flush();
//You need that line
$product->setMediaGallery(array('images' => array(), 'values' => array()));
//That line assigns your new image.As base,thumbail and image.
//Use it in the loop if you want to reassign an existing image.
$product->addImageToMediaGallery($imagePath, array('thumbnail', 'small_image', 'image'), false, false);
I hope that helps you
Cheers!

Remove original image after automatic creation of featured image

I installed the plugin http://wordpress.org/plugins/automatic-featured-image-posts/ but I am having a problemm, because the plugin doesn't remove the original image from the post content after creating the featured image. (and therefore when I don't add the featured image there appear 2 images on the post)
I tried adding this to the auto-featured-image.php
add_action('publish_post', 'eliminaroriginal');
and then
function eliminaroriginal(){ //update the post without image
$post_parent_id = $post->post_parent === 0 ? $post->ID :
$post->post_parent; $contenido = preg_replace("/[caption
.+?[/caption]|\< [img][^>][.]*>/i", "", $post->post_content,
1); $mipost = array(); $mipost['ID'] = $post_parent_id;
$mipost['post_content'] = $contenido; wp_update_post( $mipost );
}
but it didn't have any result.
Please help me, I don't know what should I do.
Thank you before hand!

CKEditor 4: Image Properties dialog and custom preview image

Just to get you up to speed, I have set-up my CKEditor instance so that when viewing the WYSIWYG (live) mode [image:abc123] is replaced with the actual URL to the image.
So for example in the HTML source view, you see this:
<img src="[image:abc123]" />
But when you view the WYSIWYG (live) mode, it shows this:
<img src="/file/image/abc123" />
This is all working great. An issue I am now having is when you edit the image in Image properties. As the image does not exist, it show's the red x.
http://img405.imageshack.us/img405/104/jzny.png
My question is, is there a way to customise the Image Properties dialog so that if it matches [image:abc123], it loads a different image URL in the Preview window?
This code doesn't work but might make it a little clearer what I'm trying to achieve here.
CKEDITOR.on('dialogDefinition', function(evt) {
if (evt.data.name == 'image') {
var image_url = ???;
var preview_image = ???;
var file_id = image_url.value.match(/\[image:([a-zA-Z0-9-]+)\]/);
if (file_id)
preview_image.src = '/file/image/' + file_id[1];
}
});
Thanks in advance!

Magento - How to show the same images for product bundles?

I created a bundled product following the instructions on the Magento site to enable it to have several sizes. See attached image:
I'm supposing that when I do the Quick simple product creation, it doesn't automatically add the same images. But since the option is only for size, the image should be the same.
The problem is, when I go to the cart or checkout page or any other page, there is no image for the product. The combination of my products with the sizes, that s over 230 products, so re-uploading all the images is a nightmare.
Question is, how can I have the system use the same image for all the different sizes?
Thanks.
I had similar problem with configurable products. I wanted the image which I assign to the main product to be added also to all options. So I created an extension and observed catalog_product_save_after event. Then I added this kind of code in my observer:
$product = $observer->getEvent()->getProduct();
if ($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE)
{
$main_image = $product->getImage();
if($main_image != "no_selection")
{
$productTypeIns = $product->getTypeInstance(true);
$childIds = $productTypeIns->getChildrenIds($product->getId());
$importDir = Mage::getBaseDir('media') . DS . 'catalog/product';
foreach ($childIds as $childId)
{
foreach($childId as $_childId)
{
$childProduct = Mage::getModel('catalog/product')->load($_childId); //You get your child products here
if ($childProduct->getImage()=="no_selection")
{
$childProduct->addImageToMediaGallery($importDir.$main_image,array ('image','small_image','thumbnail'),false,false);
$childProduct->save();
}
}
}
}
}

Magento crop image?

I found this: http://docs.magentocommerce.com/Varien/Varien_Image/Varien_Image.html#crop
But I'm not sure if this is deprecated or something because when I tried this:
echo rawurlencode($this->helper('catalog/image')->init($_product, 'image')->constrainOnly(TRUE)->keepAspectRatio(TRUE)->keepFrame(FALSE)->setWatermarkImageOpacity(0)->crop(10, 20, 30, 40)->resize(300, null))
It doesn't work and gives me this error:
Fatal error: Call to undefined method Mage_Catalog_Helper_Image::crop() in /home/xxxxx/public_html/app/design/frontend/default/xxxxx/template/catalog/product/view.phtml
So is the crop() method actually usable at all? If it is, how can I use it to crop (not to be confused with resize) the product images of Magento? Thanks!
Your mistake is assuming that $this->helper('catalog/image')->init($_product, 'image') returns a Varien_Image instance, when in fact there are two intermediate classes involved:
Mage_Catalog_Helper_Image and Mage_Catalog_Model_Product_Image.
The catalog/image helper is a mess, even though it has been cleaned up a bit in recent versions (e.g. no more private methods). Still, some getters still are protected without there being a real need for it.
Here is my workaround:
/* #var $imageHelper Mage_Catalog_Helper_Image */
// Initialize the image helper
$imageHelper = Mage::helper('catalog/image')->init($_product, 'image')
->constrainOnly(true)
->keepAspectRatio(true)
->keepFrame(false)
->setWatermarkImageOpacity(0);
// Get the catalog/product_image instance
/* #var $imageModel Mage_Catalog_Model_Product_Image */
$reflection = new ReflectionClass($imageHelper);
$property = $reflection->getProperty('_model');
$property->setAccessible(true);
$imageModel = $property->getValue($imageHelper);
// Initialize the missing values on the image model
// Usually done in Mage_Catalog_Helper_Image::__toString()
if (! $imageModel->isCached())
{
$getWatermarkMethod = $reflection->getMethod('getWatermark');
$getWatermarkMethod->setAccessible(true);
$imageModel->setBaseFile($_product->getImage())
->resize()
->setWatermark($getWatermarkMethod->invoke($imageHelper));
// Crop the image using the image processor
// $imageModel->getImageProcessor() returns a Varien_Image instance
$imageModel->getImageProcessor()->crop(10, 20, 30, 40);
// Generate the image according to the set parameters and
// get the URL while bypassing the helper to avoid reinitialization
$url = $imageModel->saveFile()->getUrl();
}
echo $url . "\n";
It would be easier to use the catalog/product_image model or Varien_Image directly, but this way all the Magento watermark settings still are applied.
Either way isn't clean.
I hope the getters on the helper are made public in future releases.
Here is the alternative method ( credits from Onlinebizsoft.com )
The following code first looking the image that available in the /resize directory, if it's not there, doing rest of things.
// actual path of image
$_imageUrl = Mage::getBaseDir('media').DS."myimage".DS.$post->getThumbnail();
// path of the resized image to be saved
// here, the resized image is saved in media/resized folder
$imageResized = Mage::getBaseDir('media').DS."myimage".DS."resized".DS.$post->getThumbnail();
// resize image only if the image file exists and the resized image file doesn't exist
// the image is resized proportionally with the width/height 135px
if (!file_exists($imageResized)&&file_exists($_imageUrl)) :
$imageObj = new Varien_Image($_imageUrl);
$imageObj->constrainOnly(TRUE);
$imageObj->keepAspectRatio(TRUE);
$imageObj->keepFrame(FALSE);
$imageObj->resize(135, 135);
$imageObj->save($imageResized);
endif;
Check the website Resize - Scale Crop images
Did you tried Varien_Image class ?
$image = new Varien_Image($img);
$cropped = $image->crop();

Resources