0

I want to upload images for custom module, so before upload image on media folder I want that resize image. How can I set resize image before upload on media folder ?

Here is my code:

public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Psr\Log\LoggerInterface $loggerInterface,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        Filesystem $filesystem,
        FileFactory $fileFactory,
        \Magento\MediaStorage\Model\File\UploaderFactory $uploaderFactory,
        \Magento\Framework\Image\AdapterFactory $adapterFactory,
        \Magento\Framework\Image\AdapterFactory $imageFactory,

       
        array $data = []
         
        )
    {
        $this->_inlineTranslation = $inlineTranslation;
        $this->_scopeConfig = $scopeConfig;
        $this->_logLoggerInterface = $loggerInterface;
        $this->messageManager = $context->getMessageManager();
        $this->_storeManager=$storeManager;
        $this->filesystem = $filesystem;
        $this->mediaDirectory = $filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
        $this->fileFactory = $fileFactory;
        $this->uploaderFactory = $uploaderFactory;
        $this->adapterFactory = $adapterFactory;
       $this->imageFactory = $imageFactory;
        
        parent::__construct($context);
         
         
    }

    
    
    public function execute()
    {   
         try {$files = $this->getRequest()->getFiles('image');
    //echo "<pre>";print_r($files);die();
    
            foreach($files as $key => $value){
            $imageAdapter = $this->adapterFactory->create();
            $imageAdapter->open($value["tmp_name"]);
            $imageAdapter->constrainOnly(TRUE);        
            $imageAdapter->keepTransparency(TRUE);        
            $imageAdapter->keepFrame(FALSE);        
            $imageAdapter->keepAspectRatio(TRUE);        
            $imageAdapter->resize(100,100); 
             $mediaDirectory = $this->filesystem->getDirectoryRead(DirectoryList::MEDIA);
            $imagepathfolder= 'test/';
            $destinationPath = $mediaDirectory->getAbsolutePath($imagepathfolder);
            $imageAdapter->save($destinationPath);
            
}echo "<pre>";print_r($result);die();
        } catch (\Exception $e) {
        echo $e->getMessage();die();
        }
            
        
        /* $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
        $resultJson->setData($printPath);
        return $resultJson; */
        }

I am getting error when I run above my code Warning: imagejpeg(C:/wamp64/www/magento234/pub/media/test): failed to open stream: Permission denied in C:\wamp64\www\magento234\vendor\magento\framework\Image\Adapter\Gd2.php on line 208

What I want:

I have created a custom module and I have set one custom form with some fields. In this form I have set file input type in the form and other input fields, so when customer filled up form with image by file input and click on submit button ,it called JavaScript method and trigger ajax and call controller method where I put my above code.When I receive form elements' values as a post method in controller that time I want that image as resize image before upload process of that image.

Note

I DO NOT WANT TO UPLOAD THAT IMAGE IN ORIGINAL SIZE AND RESIZE THAT IMAGE AND UPLOAD ON OTHER PATH. I WANT THAT IMAGE FIRST RESIZE THEN IT SHOULD UPLOAD ON SERVER

  • please provide us more information on what is the current output and what is expected. do you see exceptions? – Philipp Sander Jun 30 at 8:48
  • @PhilippSander I have updated my question and mentioned error and what I want, please check it ,thank you – Niraj Patel Jun 30 at 18:17
  • @NirajPatel what's the permissions on C:/wamp64/www/magento234/pub/media/test it looks like it's just a permissions issue. – Haim Jul 1 at 14:25
  • @Haim when I used temp_name that time it throws error about permission but If I used by file name and it upload successfully It throws permission issue because it is getting temp path in temp_name variable. When you used my code and try you will get more idea – Niraj Patel Jul 1 at 19:01
  • @niraj can you show the full error you're getting? – Haim Jul 1 at 23:15
1
+100

I have 2 solutions, one that uses the uploader and then resizes. I understand you'd rather resize right away and therefore the solution below does exactly this. I have changed only 3 lines really so you were very close (I am quite impressed by your accuracy)

you can either install the module: https://bitbucket.org/magstaging/contactwithavatar/src/master/

and reuse this code or the code below should be sufficient for you to modify your code

<?php
    
    namespace Mbs\ContactWithAvatar\Model;
    
    use Magento\Framework\App\Filesystem\DirectoryList;
    
    class NirajPatelImageManipulator
    {
        /**
         * @var \Magento\Framework\Image\AdapterFactory
         */
        private $adapterFactory;
        /**
         * @var \Magento\Framework\Filesystem
         */
        private $filesystem;
        /**
         * @var DirectoryList
         */
        private $directoryList;
        /**
         * @var \Magento\Store\Model\StoreManagerInterface
         */
        private $storeManager;
    
        public function __construct(
            \Magento\Framework\Image\AdapterFactory $adapterFactory,
            \Magento\Framework\Filesystem $filesystem,
            DirectoryList $directoryList,
            \Magento\Store\Model\StoreManagerInterface $storeManager
        ) {
            $this->adapterFactory = $adapterFactory;
            $this->filesystem = $filesystem;
            $this->directoryList = $directoryList;
            $this->storeManager = $storeManager;
        }
    
        public function resize($value, $fileName, $width = null, $height = null)
        {
            $imageAdapter = $this->adapterFactory->create();
            $imageAdapter->open($value["tmp_name"]);
            $imageAdapter->constrainOnly(TRUE);
            $imageAdapter->keepTransparency(TRUE);
            $imageAdapter->keepFrame(FALSE);
            $imageAdapter->keepAspectRatio(TRUE);
            $imageAdapter->resize(100,100);
            $mediaDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
            $imagepathfolder= 'test' . DIRECTORY_SEPARATOR;
            $destinationPath = $mediaDirectory->getAbsolutePath($imagepathfolder);
            $imageAdapter->save($destinationPath . $fileName);
    
            $resizedURL = $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA). $imagepathfolder .  $fileName;
            return $resizedURL;
        }

and I have allowed myself to return the ful url to see the image, this is something you may want to return in your ajax response

| improve this answer | |
  • what you changed in the code ? I can not see any noticable changes. My code and your code are same. I put your code in my controller and it throws same error. – Niraj Patel Jul 4 at 23:49
  • Could you please share your module with me ? Because it throws error permission issue in $value[‘temp_name’]. – Niraj Patel Jul 5 at 14:01
  • I have updated the answer with a link to the module – Herve Tribouilloy Jul 5 at 16:15
  • Thank you genius thanks for your valuable time – Niraj Patel Jul 6 at 3:28
  • as I said in my answer, that was a very good question. Really enjoyed it and more so when the bounty came my way, thank you @Niraj – Herve Tribouilloy Jul 6 at 14:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.