Magento 2: How to get resize image for Custom Module?
You can check in details by click, Resize Custom Image in Magento 2
Inside Block file keep below code,
protected $_filesystem ;
protected $_imageFactory;
public function __construct(
\Magento\Framework\Filesystem $filesystem,
\Magento\Framework\Image\AdapterFactory $imageFactory
) {
$this->_filesystem = $filesystem;
$this->_imageFactory = $imageFactory;
}
// pass imagename, width and height
public function resize($image, $width = null, $height = null)
{
$absolutePath = $this->_filesystem->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA)->getAbsolutePath('custom_module/posts/').$image;
if (!file_exists($absolutePath)) return false;
$imageResized = $this->_filesystem->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA)->getAbsolutePath('resized/'.$width.'/').$image;
if (!file_exists($imageResized)) { // Only resize image if not already exists.
//create image factory...
$imageResize = $this->_imageFactory->create();
$imageResize->open($absolutePath);
$imageResize->constrainOnly(TRUE);
$imageResize->keepTransparency(TRUE);
$imageResize->keepFrame(FALSE);
$imageResize->keepAspectRatio(TRUE);
$imageResize->resize($width,$height);
//destination folder
$destination = $imageResized ;
//save image
$imageResize->save($destination);
}
$resizedURL = $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA).'resized/'.$width.'/'.$image;
return $resizedURL;
}
Now Call inside phtml file,
$block->resize('test.jpg',500,400);
The accepted answer doesn’t consider caching the image to improve performance. You don’t need to resize and overwrite the image every time it’s requested. The following approach saves the resized image to a "cache" folder so successive calls return the image from the cache. The method is contained on a helper (not a block) so you can call it from any template you like:
app/code/Vendor/Namespace/Helper/Image.php
<?php
namespace Vendor\Namespace\Helper;
use Magento\Framework\App\Filesystem\DirectoryList;
class Image extends \Magento\Framework\App\Helper\AbstractHelper
{
/**
* Custom directory relative to the "media" folder
*/
const DIRECTORY = 'custom_module/posts';
/**
* @var \Magento\Framework\Filesystem\Directory\WriteInterface
*/
protected $_mediaDirectory;
/**
* @var \Magento\Framework\Image\Factory
*/
protected $_imageFactory;
/**
* Store manager
*
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $_storeManager;
/**
* @param \Magento\Framework\App\Helper\Context $context
* @param \Magento\Framework\Filesystem $filesystem
* @param \Magento\Framework\Image\Factory $imageFactory
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
*/
public function __construct(
\Magento\Framework\App\Helper\Context $context,
\Magento\Framework\Filesystem $filesystem,
\Magento\Framework\Image\AdapterFactory $imageFactory,
\Magento\Store\Model\StoreManagerInterface $storeManager
) {
$this->_mediaDirectory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA);
$this->_imageFactory = $imageFactory;
$this->_storeManager = $storeManager;
parent::__construct($context);
}
/**
* First check this file on FS
*
* @param string $filename
* @return bool
*/
protected function _fileExists($filename)
{
if ($this->_mediaDirectory->isFile($filename)) {
return true;
}
return false;
}
/**
* Resize image
* @return string
*/
public function resize($image, $width = null, $height = null)
{
$mediaFolder = self::DIRECTORY;
$path = $mediaFolder . '/cache';
if ($width !== null) {
$path .= '/' . $width . 'x';
if ($height !== null) {
$path .= $height ;
}
}
$absolutePath = $this->_mediaDirectory->getAbsolutePath($mediaFolder) . $image;
$imageResized = $this->_mediaDirectory->getAbsolutePath($path) . $image;
if (!$this->_fileExists($path . $image)) {
$imageFactory = $this->_imageFactory->create();
$imageFactory->open($absolutePath);
$imageFactory->constrainOnly(true);
$imageFactory->keepTransparency(true);
$imageFactory->keepFrame(true);
$imageFactory->keepAspectRatio(true);
$imageFactory->resize($width, $height);
$imageFactory->save($imageResized);
}
return $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . $path . $image;
}
}
Now from any .phtml template you can call the method like this:
<!-- Get a reference to the Image helper -->
<?php $image = $this->helper('Vendor\Namespace\Helper\Image'); ?>
.
.
.
<!-- Resize the image by specifying width only -->
<img src="<?php echo $image->resize('/my-picture.jpg', 1200); ?>">
<!-- Resize the image by specifying width and height -->
<img src="<?php echo $image->resize('/my-picture.jpg', 640, 480); ?>">
I'm afraid you don't need to create new classes for resizing your images, since Magento helpers already have it (see \Magento\Catalog\Helper\Image::resize
).
So, you can just do:
$_imageHelper = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Catalog\Helper\Image');
echo $_imageHelper->init($product, 'small_image', ['type'=>'small_image'])->keepAspectRatio(true)->resize('65','65')->getUrl();
You can also see an example of this usage at \Magento\VisualMerchandiser\Block\Adminhtml\Category\Merchandiser\Tile::getImageUrl
(Magento EE only I guess)