#StackBounty: #magento2 #cache #image-upload #file-uploader Magento 2: How to make Product image uploader rename the image file if the …

Bounty: 50

I’m using Magento v2.3.4 and Cloudflare to cache CSS, js, and images. The problem is when i tried to upload the product image from the backend using the same filename and extension, the image uploader still showing the old image, if i turn off the Cloudflare caching, this issue doesn’t exist because the file is not being cached. Is there a way to rename the image where the image is being uploaded using the same filename or extension using the product image uploader ?

enter image description here


Get this bounty!!!

#StackBounty: #magento2 #image-upload #image-resize magento 2 : resize image before upload on server

Bounty: 100

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(
        MagentoFrameworkAppActionContext $context,
        MagentoFrameworkTranslateInlineStateInterface $inlineTranslation,
        MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig,
        PsrLogLoggerInterface $loggerInterface,
        MagentoStoreModelStoreManagerInterface $storeManager,
        Filesystem $filesystem,
        FileFactory $fileFactory,
        MagentoMediaStorageModelFileUploaderFactory $uploaderFactory,
        MagentoFrameworkImageAdapterFactory $adapterFactory,
        MagentoFrameworkImageAdapterFactory $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(MagentoFrameworkAppFilesystemDirectoryList::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:wamp64wwwmagento234vendormagentoframeworkImageAdapterGd2.php on line 208

What I want:

When I upload Image, it should be first resize then go to destination folder.

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


Get this bounty!!!

#StackBounty: #magento2 #image-upload #image-resize magento 2 : resize image before upload on destination path

Bounty: 100

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(
        MagentoFrameworkAppActionContext $context,
        MagentoFrameworkTranslateInlineStateInterface $inlineTranslation,
        MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig,
        PsrLogLoggerInterface $loggerInterface,
        MagentoStoreModelStoreManagerInterface $storeManager,
        Filesystem $filesystem,
        FileFactory $fileFactory,
        MagentoMediaStorageModelFileUploaderFactory $uploaderFactory,
        MagentoFrameworkImageAdapterFactory $adapterFactory,
        MagentoFrameworkImageAdapterFactory $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(MagentoFrameworkAppFilesystemDirectoryList::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; */
        }


Get this bounty!!!

#StackBounty: #magento2 #database #image-upload #custom-field In magento 2, how save the uploaded image in db and edit the uploaded image

Bounty: 50

In magento 2, cart price rule form have custom field of ui-component image upload how to save image in db.

I follow this blog https://blog.qaisarsatti.com/magento_2/magento-2-ui-component-image-upload/

enter image description here

ui-component

<field name="promo_image">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="dataType" xsi:type="string">string</item>
                    <item name="source" xsi:type="string">specialpromotion</item>
                    <item name="label" xsi:type="string" translate="true">Image</item>
                    <item name="visible" xsi:type="boolean">true</item>
                    <item name="formElement" xsi:type="string">fileUploader</item>
                    <item name="elementTmpl" xsi:type="string">ui/form/element/uploader/uploader</item>
                    <item name="previewTmpl" xsi:type="string">Bg_SpecialPromotion/image-preview</item>
                    <item name="required" xsi:type="boolean">false</item>
                    <item name="uploaderConfig" xsi:type="array">
                        <item name="url" xsi:type="url" path=bg_specialpromotion/index/upload"/>
                    </item>
                </item>
            </argument>
   </field>

BgSpecialPromotionObserverSaveImage

<?php
namespace BgSpecialPromotionObserver;

use MagentoFrameworkEventObserver;
use MagentoFrameworkEventObserverInterface;
use MagentoFrameworkAppFilesystemDirectoryList;


class SaveImage implements ObserverInterface
{

  protected $dataPersistor;



    public function execute(Observer $observer)
    {
     $data = $observer->getRequest()->getPostValue();
     $ruleId = $data['rule_id'];
     if (isset($data['promo_image'][0]['name'])) {
            $data['promo_image'] = $data['promo_image'][0]['name'];
        } else {
            $data['promo_image'] = null;
        }
        $model = MagentoFrameworkAppObjectManager::getInstance()->get('BgSpecialPromotionModelSalesRule');
        if ($ruleId) {
             $model->load($ruleId);
         }
        $model->setData($data);
        $model->save();

    }

}

after save the uploaded image and edit the save image field not appear in admin

enter image description here

BgSpecialPromotionModelSalesRulDataProvider.php

namespace BgSpecialPromotionModelSalesRule;

use MagentoStoreModelStoreManagerInterface;

class DataProvider extends MagentoUiDataProviderAbstractDataProvider
{

    protected $salesRuleFactory;
    public function __construct(

    BgSpecialPromotionModelResourceModelSalesRuleCollectionFactory $salesRuleFactory, 

    )
    {

    $this->collection = $salesRuleFactory;

    }
    public function getData()
    {

        $items = $this->collection->getItems();

        //Replace icon with fileuploader field name
        foreach ($items as $model) {
            $this->loadedData[$model->getId()] = $model->getData();
            if ($model->getPromoImage()) {
                $m['promo_image'][0]['name'] = $model->getPromoImage();
                $m['promo_image'][0]['url'] = $this->getMediaUrl().$model->getPromoImage();
                $fullData = $this->loadedData;
                $this->loadedData[$model->getId()] = array_merge($fullData[$model->getId()], $m);
            }
        }

        return $this->loadedData;
    }

    public function getMediaUrl()
    {
        $mediaUrl = $this->storeManager->getStore()
            ->getBaseUrl(MagentoFrameworkUrlInterface::URL_TYPE_MEDIA).'test/tmp/';
        return $mediaUrl;
    }
}


Get this bounty!!!

#StackBounty: #magento2 #image-upload #custom-field In magento 2, how save the uploaded image in db and edit the uploaded image

Bounty: 50

In magento 2, cart price rule form have custom field of ui-component image upload how to save image in db.

I follow this blog https://blog.qaisarsatti.com/magento_2/magento-2-ui-component-image-upload/

enter image description here

ui-component

<field name="promo_image">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="dataType" xsi:type="string">string</item>
                    <item name="source" xsi:type="string">specialpromotion</item>
                    <item name="label" xsi:type="string" translate="true">Image</item>
                    <item name="visible" xsi:type="boolean">true</item>
                    <item name="formElement" xsi:type="string">fileUploader</item>
                    <item name="elementTmpl" xsi:type="string">ui/form/element/uploader/uploader</item>
                    <item name="previewTmpl" xsi:type="string">Bg_SpecialPromotion/image-preview</item>
                    <item name="required" xsi:type="boolean">false</item>
                    <item name="uploaderConfig" xsi:type="array">
                        <item name="url" xsi:type="url" path=bg_specialpromotion/index/upload"/>
                    </item>
                </item>
            </argument>
   </field>

BgSpecialPromotionObserverSaveImage

<?php
namespace BgSpecialPromotionObserver;

use MagentoFrameworkEventObserver;
use MagentoFrameworkEventObserverInterface;
use MagentoFrameworkAppFilesystemDirectoryList;


class SaveImage implements ObserverInterface
{

  protected $dataPersistor;



    public function execute(Observer $observer)
    {
     $data = $observer->getRequest()->getPostValue();
     $ruleId = $data['rule_id'];
     if (isset($data['promo_image'][0]['name'])) {
            $data['promo_image'] = $data['promo_image'][0]['name'];
        } else {
            $data['promo_image'] = null;
        }
        $model = MagentoFrameworkAppObjectManager::getInstance()->get('BgSpecialPromotionModelSalesRule');
        if ($ruleId) {
             $model->load($ruleId);
         }
        $model->setData($data);
        $model->save();

    }

}

after save the uploaded image and edit the save image field not appear in admin

enter image description here

BgSpecialPromotionModelSalesRulDataProvider.php

namespace BgSpecialPromotionModelSalesRule;

use MagentoStoreModelStoreManagerInterface;

class DataProvider extends MagentoUiDataProviderAbstractDataProvider
{

    protected $salesRuleFactory;
    public function __construct(

    BgSpecialPromotionModelResourceModelSalesRuleCollectionFactory $salesRuleFactory, 

    )
    {

    $this->collection = $salesRuleFactory;

    }
    public function getData()
    {

        $items = $this->collection->getItems();

        //Replace icon with fileuploader field name
        foreach ($items as $model) {
            $this->loadedData[$model->getId()] = $model->getData();
            if ($model->getPromoImage()) {
                $m['promo_image'][0]['name'] = $model->getPromoImage();
                $m['promo_image'][0]['url'] = $this->getMediaUrl().$model->getPromoImage();
                $fullData = $this->loadedData;
                $this->loadedData[$model->getId()] = array_merge($fullData[$model->getId()], $m);
            }
        }

        return $this->loadedData;
    }

    public function getMediaUrl()
    {
        $mediaUrl = $this->storeManager->getStore()
            ->getBaseUrl(MagentoFrameworkUrlInterface::URL_TYPE_MEDIA).'test/tmp/';
        return $mediaUrl;
    }
}


Get this bounty!!!

#StackBounty: #magento2 #image-upload #custom-field In magento 2, after save the uploaded image and edit the save image field not appea…

Bounty: 50

In magento 2, cart price rule form have custom field of ui-component image upload how to save image in db.

I follow this blog https://blog.qaisarsatti.com/magento_2/magento-2-ui-component-image-upload/

enter image description here

ui-component

<field name="promo_image">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="dataType" xsi:type="string">string</item>
                    <item name="source" xsi:type="string">specialpromotion</item>
                    <item name="label" xsi:type="string" translate="true">Image</item>
                    <item name="visible" xsi:type="boolean">true</item>
                    <item name="formElement" xsi:type="string">fileUploader</item>
                    <item name="elementTmpl" xsi:type="string">ui/form/element/uploader/uploader</item>
                    <item name="previewTmpl" xsi:type="string">Bg_SpecialPromotion/image-preview</item>
                    <item name="required" xsi:type="boolean">false</item>
                    <item name="uploaderConfig" xsi:type="array">
                        <item name="url" xsi:type="url" path=bg_specialpromotion/index/upload"/>
                    </item>
                </item>
            </argument>
   </field>

BgSpecialPromotionObserverSaveImage

<?php
namespace BgSpecialPromotionObserver;

use MagentoFrameworkEventObserver;
use MagentoFrameworkEventObserverInterface;
use MagentoFrameworkAppFilesystemDirectoryList;


class SaveImage implements ObserverInterface
{

  protected $dataPersistor;



    public function execute(Observer $observer)
    {
     $data = $observer->getRequest()->getPostValue();
     $ruleId = $data['rule_id'];
     if (isset($data['promo_image'][0]['name'])) {
            $data['promo_image'] = $data['promo_image'][0]['name'];
        } else {
            $data['promo_image'] = null;
        }
        $model = MagentoFrameworkAppObjectManager::getInstance()->get('BgSpecialPromotionModelSalesRule');
        if ($ruleId) {
             $model->load($ruleId);
         }
        $model->setData($data);
        $model->save();

    }

}

after save the uploaded image and edit the save image field not appear in admin

enter image description here


Get this bounty!!!

#StackBounty: #magento2 #image-upload In admin form after edit and save a form in db, already stored image save as blank in db in magen…

Bounty: 50

when a edit admin form, Previously saved image path become blank in db how to solve this problem in magento 2
I m done a image upload and save into db by using this code

  1. In form upload and save a image in database

enter image description here

  1. after edit and save a form again, image will be blank
    enter image description here

Please someone help me solve this issue


Get this bounty!!!