Showing posts with label Images. Show all posts
Showing posts with label Images. Show all posts

Thursday 5 September 2019

How to upload image file with ajax

jQuery("form#add-group-form").submit(function(e){
        e.preventDefault();
        var formData = new FormData(jQuery(this)[0]);
       
        jQuery.ajax({
            type:"POST",
            url:jQuery(this).attr("action"),
            data:formData,
            processData: false,
            contentType: false,
            dataType: "json",
            success: function(response){
                alert(response);
            }
        });
    });

Saturday 23 June 2018

How to Import / Insert / Add product image from URL in Magento 2

use Magento\Framework\App\Action\Context;

class Createproduct extends \Magento\Framework\App\Action\Action {

    protected $directoryList;
    protected $file;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $pageFactory,
        \Magento\Framework\App\Filesystem\DirectoryList $directoryList,
        \Magento\Framework\Filesystem\Io\File $file) {

        $this->_resultpageFactory = $pageFactory;
        $this->directoryList = $directoryList;
        $this->file = $file;
        return parent::__construct($context);
    }


    protected function getMediaDirTmpDir()
    {
        return $this->directoryList->getPath($this->directoryList::MEDIA) . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR;
    }

    public function setImage($product, $imageUrl, $visible = false, $imageType = [])
    {
        $tmpDir = $this->getMediaDirTmpDir();

        $this->file->checkAndCreateFolder($tmpDir);

        $newFileName = $tmpDir . baseName($imageUrl);


        $result = $this->file->read($imageUrl, $newFileName);
        if ($result) {
            $product->addImageToMediaGallery($newFileName, $imageType, true, $visible);
        }
        return $result;
    }

    public function execute() {
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $product = $objectManager->create('\Magento\Catalog\Model\Product')->load(1);
        $imagePath = "https://domain.com/image.jpg"; // path of the image
            $this->setImage($product, $imagePath, false, $imageType = ['image', 'small_image', 'thumbnail']);
            $product->save();
    }
}

How to check image is valid or not in php from URL in PHP

$imagePath = "https://jaydip.kansagra.com/image.jpg";
if (@getimagesize($imagePath)) {
   echo 'Image exists';
} else {
      echo 'Image not exists';
}

Tuesday 9 January 2018

Clear configurable Swatches, Images, Flush Magento ALL Cache and cache files

ini_set('display_errors', 1);
require_once('../app/Mage.php');
Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID));
/* Clear Cache */
try {
    $allTypes = Mage::app()->useCache();
    foreach($allTypes as $type => $cache) {
        Mage::app()->getCacheInstance()->cleanType($type);
    }
   
    /**
     * Flush cache storage
     */
    Mage::dispatchEvent('adminhtml_cache_flush_all');
    Mage::app()->getCacheInstance()->flush();
   
    /**
     * Flush all magento cache
     */
    Mage::app()->cleanCache();
    Mage::dispatchEvent('adminhtml_cache_flush_system');
   
   
} catch (Exception $e) {
    Mage::logException($e->getMessage());
}
try {
    /* cleanImages */
    Mage::getModel('catalog/product_image')->clearCache();
    Mage::dispatchEvent('clean_catalog_images_cache_after');
   
    /* cleanSwatches */
    Mage::helper('configurableswatches/productimg')->clearSwatchesCache();
    Mage::dispatchEvent('clean_configurable_swatches_cache_after');
   
    clearCstoreCacheDir('../var/cache');
   
    echo 'Success';
   
} catch (Mage_Core_Exception $e) {
    echo $e->getMessage();
} catch (Exception $e) {
    echo Mage::helper('adminhtml')->__('An error occurred while clearing the configurable swatches image cache.');
}
function clearCstoreCacheDir($dirPath) {
    if (!is_dir($dirPath)) {
        throw new InvalidArgumentException("$dirPath must be a directory");
    }
    if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
        $dirPath .= '/';
    }
    $files = glob($dirPath . '*', GLOB_MARK);
    foreach ($files as $file) {
        if (is_dir($file)) {
            self::deleteDir($file);
        } else {
            unlink($file);
        }
    }
    rmdir($dirPath);
}

Saturday 8 October 2016

How to upload products multiple images in codeigniter Gocart in admin panel

Open : gocart/views/admin/iframe/product_image_uploader.php

<?php include('header.php');?>
<script type="text/javascript">
 
<?php if( $this->input->post('submit') ):?>
$(window).ready(function(){
        $('#iframe_uploader', window.parent.document).height($('body').height()); });
<?php endif;?>
<?php if($file_name):?>
        parent.add_product_image('<?php echo json_encode($file_name);?>');
<?php endif;?>
 
</script>
<?php if (!empty($error)): ?>
    <div class="alert alert-error">
        <a class="close" data-dismiss="alert">×</a>
        <?php echo $error; ?>
    </div>
<?php endif; ?>
<div class="row-fluid">
    <div class="col-md-12">
        <?php echo form_open_multipart($this->config->item('admin_folder') . '/products/product_image_upload', 'class="form-inline "'); ?>
        <?php echo form_upload(array('name' => 'userfile[]', 'id' => 'userfile', 'class' => 'input-file', 'multiple'=>"true" )); ?>
        <input class="btn" name="submit" type="submit" value="<?php echo lang('upload'); ?>" />
        </form>
    </div>
</div>
<?php include('footer.php');


Open : gocart/controllers/admin/products.php

Update product_image_upload() function

function product_image_upload() {
        $data['file_name'] = false;
        $data['error'] = false;
        $config['allowed_types'] = 'gif|jpg|png';
        //$config['max_size'] = $this->config->item('size_limit');
        $config['upload_path'] = 'uploads/images/full';
        $config['encrypt_name'] = true;
        $config['remove_spaces'] = true;
        $this->load->library('upload', $config);
        $files = $_FILES;
     
        $cpt = count($_FILES['userfile']['name']);
        for($i=0; $i<$cpt; $i++)
        {
            $_FILES['userfile']['name']= $files['userfile']['name'][$i];
            $_FILES['userfile']['type']= $files['userfile']['type'][$i];
            $_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i];
            $_FILES['userfile']['error']= $files['userfile']['error'][$i];
            $_FILES['userfile']['size']= $files['userfile']['size'][$i];

            //$this->upload->initialize($this->set_upload_options());
         
            if ($this->upload->do_upload()) {
                $upload_data = $this->upload->data();
             
                $this->load->library('image_lib');
                /*
                  I find that ImageMagick is more efficient that GD2 but not everyone has it
                  if your server has ImageMagick then you can change out the line
                  $config['image_library'] = 'gd2';
                  with
                  $config['library_path'] = '/usr/bin/convert'; //make sure you use the correct path to ImageMagic
                  $config['image_library'] = 'ImageMagick';
                 */
                //this is the larger image
                $config['image_library'] = 'gd2';
                $config['source_image'] = 'uploads/images/full/' . $upload_data['file_name'];
                $config['new_image'] = 'uploads/images/medium/' . $upload_data['file_name'];
                $config['maintain_ratio'] = TRUE;
                $config['width'] = 600;
                $config['height'] = 500;
                $this->image_lib->initialize($config);
                $this->image_lib->resize();
                $this->image_lib->clear();
                //small image
                $config['image_library'] = 'gd2';
                $config['source_image'] = 'uploads/images/medium/' . $upload_data['file_name'];
                $config['new_image'] = 'uploads/images/small/' . $upload_data['file_name'];
                $config['maintain_ratio'] = TRUE;
                $config['width'] = 235;
                $config['height'] = 235;
                $this->image_lib->initialize($config);
                $this->image_lib->resize();
                $this->image_lib->clear();
                //cropped thumbnail
                $config['image_library'] = 'gd2';
                $config['source_image'] = 'uploads/images/small/' . $upload_data['file_name'];
                $config['new_image'] = 'uploads/images/thumbnails/' . $upload_data['file_name'];
                $config['maintain_ratio'] = TRUE;
                $config['width'] = 150;
                $config['height'] = 150;
                $this->image_lib->initialize($config);
                $this->image_lib->resize();
                $this->image_lib->clear();
                $data['file_name'][] = $upload_data['file_name'];
            }
        }
        if ($this->upload->display_errors() != '') {
            $data['error'] = $this->upload->display_errors();
        }
        $this->load->view($this->config->item('admin_folder') . '/iframe/product_image_uploader', $data);
    }


Open : gocart/views/admin/product_form.php

Update : add_product_image(data) function


function add_product_image(data) {
     
        var $images = $.parseJSON(data);
        $.each($images, function(i, image) {
            p = image.split('.');
            var photo = '<?php add_image("' + p[0] + '", "' + p[0] + '.' + p[1] + '", '
            ', '
            ', '
            ', base_url('
            uploads / images / thumbnails '));?>';
            $('#gc_photos').append(photo);
            $('#gc_photos').sortable('destroy');
            photos_sortable();
        });
    }