staempfli / magento2-module-image-resizer

Magento 2 Module to add simple image resizing capabilities in all blocks and .phtml templates
92 stars 32 forks source link

Images dont resize if the url path is given for an image assigned to the catalog/product/ #10

Closed pmathbliss closed 6 years ago

pmathbliss commented 6 years ago

Staempfli\ImageResizer\Model\Resizer: initRelativeFilenameFromUrl() this gets the image path based relative to the /cache/ folder.

protected function initRelativeFilenameFromUrl(string $imageUrl)
    {
        $this->relativeFilename = false; // reset filename in case there was another value defined
        $mediaUrl = $this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA);
        $mediaPath = parse_url($mediaUrl, PHP_URL_PATH);
        $imagePath = parse_url($imageUrl, PHP_URL_PATH);

        if (false !== strpos($imagePath, $mediaPath)) {

            $this->relativeFilename = str_replace($mediaPath, '', $imagePath);
            if(strstr($this->relativeFilename,"/cache/"))
            {
                list($first,$second) = explode("/cache/",$this->relativeFilename);

                $path = explode("/",$second);
                array_shift($path);
                $this->relativeFilename = $first . "/" . implode("/",$path);
            }

        }

    }
jalogut commented 6 years ago

Hi @pmathbliss Functionality to resize product images was not added out of the box because Magento already resizes those images. However, if you need that, you can use the following code in your custom Block:

    public function getImageUrl(int $width, int $height) : string
    {
        $customAttribute = $this->getProduct()->getCustomAttribute('image');
        if (!$customAttribute) {
            return '';
        }

        $imageFilename = $customAttribute->getValue();
        if (!$imageFilename) {
            return '';
        }

        $imagePath = $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA)
            . 'catalog'
            . DIRECTORY_SEPARATOR
            . 'product'
            . $imageFilename;

        /** @var \Staempfli\ImageResizer\Model\Resizer $imageResizer */
        $imageResizer = $this->getImageResizer();
        return $imageResizer->resizeAndGetUrl($imagePath, $width, $height);
    }

If you would like to have that functionality to resize product images by default, you can open a Pull Request with your suggested code. Let me know if you need help with that.