Skip to content

Instantly share code, notes, and snippets.

@ajbonner
Last active July 8, 2016 18:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ajbonner/94c8e61705bb7aa3e6feca4461d85595 to your computer and use it in GitHub Desktop.
Save ajbonner/94c8e61705bb7aa3e6feca4461d85595 to your computer and use it in GitHub Desktop.
Fix tiresome headers already sent bug in Magento 1.x
<?php
/**
* Generate image thumbnail on the fly
*/
public function thumbnailAction()
{
$file = $this->getRequest()->getParam('file');
$file = Mage::helper('cms/wysiwyg_images')->idDecode($file);
$thumb = $this->getStorage()->resizeOnTheFly($file);
if ($thumb !== false) {
$image = Varien_Image_Adapter::factory('GD2');
$image->open($thumb);
ob_start();
$image->display();
$imageData = ob_get_contents();
ob_end_clean();
$mimeType = image_type_to_mime_type($image->getMimeType());
$this->getResponse()->setHeader('Content-Type', $mimeType, true);
$this->getResponse()->setBody($imageData);
} else {
// todo: genearte some placeholder
}
}
@ajbonner
Copy link
Author

ajbonner commented Jul 8, 2016

Basically the problem is in $image->display() an explict header('Content-Type', $mimeType) is set. It actually is even buggier still, as in the case of a PNG, it sets the content-type to 3 (gd's PNG filetype code).

This fix works around the problem by capturing the image data using output buffering, then uses the fact that getMimeType() returns a file type id rather than actual mimetype to query the correct mimetype from the gd type database.

There's more elegant solutions to this, but I wanted to change the absolute minimum of core magento code and have those changes as localized as possible.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment