You can get all image related methods for category and product from helper file inside Magento_Catalog module core file,
vendor/magento/module-catalog/Helper/Image.php
List of methods are
<img src="<?php echo $_imagehelper->init($_product, 'thumbnail')->keepAspectRatio(true)->resize('400', '400'); ?>" />
this is to use in version 2.2. the image type was changed
<img src="<?php echo $_imagehelper->init($_product, 'product_base_image')->keepAspectRatio(true)->resize('400', '400'); ?>" />
For custom Image Resize section
Inside Block file,
protected $_filesystem ;
protected $_imageFactory;
public function __construct(
\Magento\Framework\Filesystem $filesystem,
\Magento\Framework\Image\AdapterFactory $imageFactory ,
\Magento\Store\Model\StoreManagerInterface $storeManager,
) {
$this->_filesystem = $filesystem;
$this->_imageFactory = $imageFactory;
$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::MEDIA)->getAbsolutePath('custom_module/posts/').$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;
}
Call inside template file $block->resize('img.jpg',300,300);