Pergunta

Could anyone tell me please which class/method in Magento should be overridden (in a plugin) in order to automatically resize images at upload please ?

The aim is to set a max width/height in Magento Settings and then use these settings in this class/method.

This question has been asked at least 2 or 3 times, but I don't consider "Magento automatically make different versions" as an acceptable answer for multiples reasons:

  • backend users sometimes upload HD images like 10Mpixels or so
  • 10Mpixels images will NEVER (at least not until a few years) be necessary in a simple web shop
  • it takes hard disk, backup disk and can fill disk quota quite quickly, locking up Magento
  • it does not make sense to discuss "why" when the question is just "how"

Thank you :)

Foi útil?

Solução

We have created a simple Magento plugin to enable image resize at upload. You can configure a max width and height or keep it disabled : https://github.com/ircf/magento-resize-at-upload

This plugin will be added in magento connect soon.

Anyone can choose to use it or not, this is another question.

Outras dicas

We have done something similar without Magento but directly PHP, maybe you can do the same, I don't know what your mileage is.

On Linux install ImageMagick and read about the command-line tools on that site here: Magick commands.

Once you know the command syntax you need, follow these steps:

  • upload binary to temp directory with unique name (use PHP's uniqueid());
  • fire the conversion with PHP's exec() statement;
  • move the file to the definitive destination folder (use PHP's rename() statement);
  • unklink (remove) the temporary file (use PHP's unlink() statement).

This was much work but once done, it works very well now on many systems we have.

Magento's product image resizing is already very powerful and under no circumstances should you be thinking about replacing it. It makes no sense.

Any backend user uploading 10Mega-pixel image without optimisation should not be a web master. Any product photography should always be optimised for the web and even more optimised to fit your stores template.

Lets look at the how from a different angle - You upload a 1200px X 1200px image to magento admin (optimised should be less than 150kb) and while on the frontend your responsive template shows a maximum product image of around 600px the retina version would still be 1200px.

Using the picture element or webkits accepted srcset you can quickly define a new resolution at different screen widths and density all from a single high resolution image since this creates these sizes on the fly and stores in cache.

If storage is an issue you can always flush your cache to save storage and clean up old product images however if storage is a problem I recommend upgrading your hosting as it makes no sense to look for hacks in the system to accommodate poor hardware infrastructure.

Consider using CDN's and other cloud based systems as a means for backups and just ignore the media folder in your own local backups.

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?

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top