Как изменить размер изображения в Magento 2?


Я хочу изменить размер изображения подкатегории. для этого, Я добавил этот код в файл .phtml.Я получаю неправильный путь для изображения

<?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>

Я получаю

Http://Hostname/als2/pub/static/version1549014696/frontend/Theme/Name/en_US/Magento_Catalog/images/product/placeholder/.jpg

Author: Aasim Goriya, 2019-02-01

3 answers

Создайте изображение с измененным размером, передав URL-адрес изображения

Создать файл блока app\code\Ketan\Resize\Helper\Image.php

Передать URL-адрес и размер

<?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];
    }
}

В вашем phtml файле

<?php foreach ($subcats as $subcat) { 
$_imgUrl = $subcat->getImageUrl(); ?>

<img src="<?php echo $this->helper('Ketan\Resize\Helper\Image')->imageResize($_imgUrl,'256','128','subtcat/'); ?>">

<?php } ?>
 3
Author: Ketan Borada, 2020-06-15 08:30:17

Пожалуйста, попробуйте этот код для изменения размера любых изображений.

Использование $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;

Использование помощника:

<?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;
    } 
}
?>

, А затем добавьте следующий код в свой .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>

Пожалуйста, проверьте и дайте мне знать, если возникнут какие-либо проблемы.

 1
Author: Aasim Goriya, 2019-02-01 12:41:46

Я написал код для изменения размеров любых изображений продуктов в Magento 2 в соответствии с желаемой шириной и высотой. Я опишу, как изменить размер изображений в Magento2, Обновить изображение продукта в Magento2, Удалить белую рамку в Magento 2, изменить размеры изображения продукта в Magento 2, например, изменить размер пользовательского изображения и отобразить его на сайте в областях специального размера.

Для Magento 2 вы можете использовать следующий код для изменения размера изображений в Magento 2

Шаг 1: Вам необходимо создать файл вспомогательного класса Image.php в Vender\Module\Helper\Image.php и прошлое ниже кода.

< ?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];
    }
}

Шаг 2: Используя приведенный ниже код, вы можете вызвать метод imageResize() из любого класса, блока или шаблона.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$imgpath = $objectManager->create('Vender\Module\Helper\Image')->imageResize('IMAGE_PATH','50','50','YOUR_DIR_NAME/');

Теперь я собираюсь объяснить методы, которые я использовал 1. Получить директорию чтения() 2. Получить абсолютный путь() 3. Цвет фона() 4. Ограниченно() 5. Сохраняйте прозрачность() 6. Сохраняемый кадр() 7. Сохранение спектрации()

Magento 2 – Правильно удалите белое изображение с кадр

< ?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; ?>

Если вы хотите изменить размер изображения в magento 2 и хотите получить дополнительную информацию об этом, прочитайте наш блог: КАК ИЗМЕНИТЬ РАЗМЕР ИЗОБРАЖЕНИЙ В MAGENTO 2?

 -1
Author: Kristy Davis, 2019-07-29 13:36:34