Does any one know how we can resize product image by product id ? i do not want to use resize command,becuase it takes much time
1 Answer
protected $_productRepository;
protected $_productImageHelper;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Catalog\Model\ProductRepository $productRepository,
\Magento\Catalog\Helper\Image $productImageHelper,
array $data = []
)
{
$this->_productRepository = $productRepository;
$this->_productImageHelper = $productImageHelper;
parent::__construct($context, $data);
}
public function getProductById($id)
{
return $this->_productRepository->getById($id);
}
public function getProductBySku($sku)
{
return $this->_productRepository->get($sku);
}
/**
* Schedule resize of the image.
* @see \Magento\Catalog\Model\Product\Image
* @param int $width
* @param int $height
* @return $this
*/
public function resizeImage($product, $imageId, $width, $height = null)
{
$resizedImage = $this->_productImageHelper->init($product, $imageId)
->constrainOnly(TRUE)
->keepAspectRatio(TRUE)
->keepTransparency(TRUE)
->keepFrame(FALSE)
->resize($width, $height);
return $resizedImage;
}