How to resize Image in Magento 2?
-
16-02-2021 - |
题
I want to resized image of subcategory. for that, I added this code in .phtml file.I'm getting wrong path for image
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$catId = 3; //Parent Category ID
$subCategory = $objectManager->create('Magento\Catalog\Model\Category')->load($catId);
$subCats = $subCategory->getChildrenCategories();
$_helper = $this->helper('Magento\Catalog\Helper\Output');
$_imagehelper = $this->helper('Magento\Catalog\Helper\Image');
$count = 0;
?>
<div class="container homecat">
<div class="row">
<?php
foreach ($subCats as $subcat) {
$_category = $objectManager->create('Magento\Catalog\Model\Category')->load($subcat->getId());
$subcaturl = $subcat->getUrl();
$_imgHtml = '';
$subcaturl = $_imagehelper->init($_category, 'image')->keepAspectRatio(TRUE)
->constrainOnly(TRUE)
->keepAspectRatio(TRUE)
->keepTransparency(TRUE)
->resize('256','128')
->getUrl();
echo $subcaturl ."<br/>";
$_imgHtml = '<img src="' . $subcaturl . '" />';
$_imgHtml = $_helper->categoryAttribute($_category, $_imgHtml, 'image');
echo $_imgHtml;
} ?>
</div>
</div>
I am getting
解决方案
Create resize image by passing image URL
create Block file
app\code\Ketan\Resize\Helper\Image.php
pass url and dimension
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Ketan\Resize\Helper;
use Magento\Framework\Filesystem;
use Magento\Framework\Url;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Filesystem\DirectoryList;
class Image extends \Magento\Framework\App\Helper\AbstractHelper {
protected $scopeConfig;
protected $storeManager;
protected $messageManager;
protected $_response;
protected $_resourceConfig;
protected $_responseFactory;
protected $_url;
protected $_filesystem;
protected $_directory;
protected $_imageFactory;
public function __construct(
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Framework\Message\ManagerInterface $messageManager,
\Magento\Framework\App\ResponseInterface $response,
\Magento\Framework\App\Config\Storage\WriterInterface $resourceConfig,
\Magento\Framework\App\ResponseFactory $responseFactory,
\Magento\Framework\UrlInterface $url,
\Magento\Framework\Filesystem $filesystem,
\Magento\Framework\Image\AdapterFactory $imageFactory
)
{
$this->scopeConfig = $scopeConfig;
$this->_storeManager=$storeManager;
$this->messageManager=$messageManager;
$this->_response=$response;
$this->_resourceConfig=$resourceConfig;
$this->_responseFactory = $responseFactory;
$this->_url = $url;
$this->_filesystem = $filesystem;
$this->_directory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA);
$this->_imageFactory = $imageFactory;
}
public function imageResize(
$src,
$width=35,
$height=35,
$dir='resize/'
){
if (!@getimagesize($src)) {
$src = $this->_storeManager->getStore()->getBaseUrl().'pub/media/catalog/product/placeholder/'.$this->scopeConfig->getValue('catalog/placeholder/small_image_placeholder',\Magento\Store\Model\ScopeInterface::SCOPE_STORE);
}
$absPath = $src;
$imageResized = $this->_filesystem
->getDirectoryRead(DirectoryList::MEDIA)
->getAbsolutePath($dir).
$this->getNewDirectoryImage($src);
$imageResize = $this->_imageFactory->create();
$imageResize->open($absPath);
$imageResize->backgroundColor([255, 255, 255]);
$imageResize->constrainOnly(TRUE);
$imageResize->keepTransparency(TRUE);
$imageResize->keepFrame(true);
$imageResize->keepAspectRatio(true);
$imageResize->resize($width,$height);
$dest = $imageResized ;
$imageResize->save($dest);
$resizedURL= $this->_storeManager->getStore()
->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA).
$dir.$this->getNewDirectoryImage($src);
return $resizedURL;
}
public function getNewDirectoryImage($src){
$segments = array_reverse(explode('/',$src));
$first_dir = substr($segments[0],0,1);
$second_dir = substr($segments[0],1,1);
return 'cache/'.$first_dir.'/'.$second_dir.'/'.$segments[0];
}
}
In your phtml
file
<?php foreach ($subcats as $subcat) {
$_imgUrl = $subcat->getImageUrl(); ?>
<img src="<?php echo $this->helper('Ketan\Resize\Helper\Image')->imageResize($_imgUrl,'256','128','subtcat/'); ?>">
<?php } ?>
其他提示
Please try this code for resized any images.
Using $objectManager :
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$directory = $objectManager->get('\Magento\Framework\Filesystem\DirectoryList');
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$fileSystem = $objectManager->get('Magento\Framework\Filesystem');
$absolutePath = $objectManager->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::ROOT)->getAbsolutePath('pub/media/').$subcat->getUrl();
$imageResized = $objectManager->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA)->getAbsolutePath('resized/'.$width.'/').$subcat->getUrl();
//create image factory...
$imageResize = $objectManager->create('\Magento\Framework\Image\AdapterFactory');
$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 = $storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA).'resized/'.$width.'/'.$image;
echo $resizedURL;
Using Helper :
<?php
namespace Vendor\Module\Helper;
use Magento\Store\Model\StoreManagerInterface;
class Imageresize extends \Magento\Framework\App\Helper\AbstractHelper
{
protected $_filesystem ;
protected $_imageFactory;
protected $_storeManager;
protected $_objectManager;
public function __construct(
\Magento\Framework\Filesystem $filesystem,
\Magento\Framework\ObjectManagerInterface $objectManager,
StoreManagerInterface $storeManager,
\Magento\Framework\Image\AdapterFactory $imageFactory
) {
$this->_filesystem = $filesystem;
$this->_imageFactory = $imageFactory;
$this->_objectManager = $objectManager;
$this->_storeManager = $storeManager;
}
// pass imagename, width and height
public function resize($image, $width = null, $height = null)
{
$absolutePath = $this->_filesystem->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::ROOT)->getAbsolutePath('pub/media/').$image;
$imageResized = $this->_filesystem->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA)->getAbsolutePath('resized/'.$width.'/').$image;
//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;
}
}
?>
And then add following code in your .phtml
<?php $imgResized = $this->helper('Vendor\Module\Helper\Imageresize')->resize($subcaturl,277,180); ?>
<a href="<?php echo $br['link']; ?>"><img src="<?php echo $imgResized; ?>" /></a>
Please check and let me know if any issue.
I have written code for resizing any products images in Magento 2 according to your desired width and height. I will describe how to resize images In Magento2, Update product image in Magento2, Remove white frame in Magento 2, change product image dimensions Magento 2 such as needing to resize a custom image and display it on the site in special sized areas.
For Magento 2, you can use the following code to resize your images in Magento 2
Step 1: You need to create helper class file Image.php at Vender\Module\Helper\Image.php and the past below code.
< ?php
namespace Vender\Module\Helper;
use Magento\Framework\Filesystem;
use Magento\Framework\Url;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Filesystem\DirectoryList;
class Image extends \Magento\Framework\App\Helper\AbstractHelper {
protected $scopeConfig;
protected $storeManager;
protected $messageManager;
protected $_response;
protected $_resourceConfig;
protected $_responseFactory;
protected $_url;
protected $_filesystem;
protected $_directory;
protected $_imageFactory;
public function __construct(
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Framework\Message\ManagerInterface $messageManager,
\Magento\Framework\App\ResponseInterface $response,
\Magento\Framework\App\Config\Storage\WriterInterface $resourceConfig,
\Magento\Framework\App\ResponseFactory $responseFactory,
\Magento\Framework\UrlInterface $url,
\Magento\Framework\Filesystem $filesystem,
\Magento\Framework\Image\AdapterFactory $imageFactory
)
{
$this->scopeConfig = $scopeConfig;
$this->_storeManager=$storeManager;
$this->messageManager=$messageManager;
$this->_response=$response;
$this->_resourceConfig=$resourceConfig;
$this->_responseFactory = $responseFactory;
$this->_url = $url;
$this->_filesystem = $filesystem;
$this->_directory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA);
$this->_imageFactory = $imageFactory;
}
public function imageResize(
$src,
$width=35,
$height=35,
$dir='resized/'
){
$absPath = $this->_filesystem
->getDirectoryRead(DirectoryList::MEDIA)
->getAbsolutePath().$src;
$imageResized = $this->_filesystem
->getDirectoryRead(DirectoryList::MEDIA)
->getAbsolutePath($dir).
$this->getNewDirectoryImage($src);
$imageResize = $this->_imageFactory->create();
$imageResize->open($absPath);
$imageResize->backgroundColor([255, 255, 255]);
$imageResize->constrainOnly(TRUE);
$imageResize->keepTransparency(TRUE);
$imageResize->keepFrame(true);
$imageResize->keepAspectRatio(true);
$imageResize->resize($width,$height);
$dest = $imageResized ;
$imageResize->save($dest);
$resizedURL= $this->_storeManager->getStore()
->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA).
$dir.$this->getNewDirectoryImage($src);
return $resizedURL;
}
public function getNewDirectoryImage($src){
$segments = array_reverse(explode('/',$src));
$first_dir = substr($segments[0],0,1);
$second_dir = substr($segments[0],1,1);
return 'cache/'.$first_dir.'/'.$second_dir.'/'.$segments[0];
}
}
Step 2: Using below code you can call above imageResize() method from any class, block or template.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$imgpath = $objectManager->create('Vender\Module\Helper\Image')->imageResize('IMAGE_PATH','50','50','YOUR_DIR_NAME/');
Now I am going to explain the methods I have used 1. getDirectoryRead() 2. getAbsolutePath() 3. backgroundColor() 4. constrainOnly() 5. keepTransparency() 6. keepFrame() 7. keepAspectRatio()
Magento 2 – Properly remove white image from frame
< ?php foreach ($this->getGalleryImages() as $_image): ?>
•
helper('catalog/image')->init($this->getProduct(), 'thumbnail', $_image->getFile())->resize(56); ?>" width="56" height="56" alt="< ?php echo $this->htmlEscape($_image->getLabel()) ?>" />
< ?php endforeach; ?>
If you want resizing image in magento 2 and you want further information about this then read our blog : HOW TO RESIZE IMAGES IN MAGENTO 2?