As per my requirements, I have made a code to upload an image and given the various effects to the image.
So please follow the below steps to achieve the functionality.
Step1: Add below code in your .phtml file where you want to upload an image.
<div class="container wallpapercustompage">
<div class="row">
<div class="col-lg-8">
<div class="mainImage">
<img src="<?php echo $this->getUrl(); ?>10221276943_45e198c6c6_4k.jpg" id="mainImageSrc" />
</div>
<div class="actions-save" style="display:none;">
<button type="button" class="action-cancel" data-role="cancel-button" data-image="10221276943_45e198c6c6_4k.jpg" data-type="jpg" title="<?php echo __('Cancel'); ?>"><span><?php echo __('Cancel'); ?></span></button>
<button type="button" class="action-apply" data-role="apply-button" data-image="10221276943_45e198c6c6_4k.jpg" data-type="jpg" title="<?php echo __('Apply'); ?>"><span><?php echo __('Apply'); ?></span></button>
</div>
<div class="actions">
<button type="button" class="action-flip" data-role="flip-button" data-image="10221276943_45e198c6c6_4k.jpg" data-type="jpg" title="<?php echo __('Flip image'); ?>"><span><?php echo __('Flip image'); ?></span></button>
<button type="button" class="action-bw" data-role="bw-button" data-image="10221276943_45e198c6c6_4k.jpg" data-type="jpg" title="<?php echo __('Black & White Filter'); ?>"><span><?php echo __('Black & White Filter'); ?></span></button>
<button type="button" class="action-sepia" data-role="sepia-button" data-image="10221276943_45e198c6c6_4k.jpg" data-type="jpg" title="<?php echo __('Sepia Filter'); ?>"><span><?php echo __('Sepia Filter'); ?></span></button>
</div>
</div>
<div class="col-lg-4">
<form class="form-horizontal" id="frm_attachment" name="frm_attachment" method="post" enctype="multipart/form-data" action="<?php echo $this->getUrl(); ?>wallpaper/index/customize">
<div class="browse-wrap">
<input accept="image/*" id="attachment" name="attachment" type="file" value="">
</div>
<div class="row">
<button type="submit" id="uploadAttachment" class="btn btn-primary"><?php echo __('Submit'); ?></button>
</div>
</form>
<div id="attachmentFiles"></div>
</div>
</div>
</div>
<style type="text/css">
.mainImage-image-grayscale{ -webkit-filter: grayscale(100%); -moz-filter: grayscale(100%); -o-filter: grayscale(100%); -ms-filter: grayscale(100%); filter: grayscale(100%); }
.mainImage-image-sepia{ -webkit-filter: sepia(100%); -moz-filter: sepia(100%); -o-filter: sepia(100%); -ms-filter: sepia(100%); filter: sepia(100%); }
.mainImage-image-flip{ transform: scale(-1, 1); -moz-transform: scale(-1, 1); -webkit-transform: scale(-1, 1); -o-transform: scale(-1, 1); -khtml-transform: scale(-1, 1); -ms-transform: scale(-1, 1); }
</style>
<script>
function getSizeInCM (sizeInPX) {
return sizeInPX * 2.54 / (96 * window.devicePixelRatio)
};
require(['jquery'], function ($) {
$(document).ready(function ($) {
/**** Delete Image & Image Effects ****/
$(document).on('click', '#attachmentFiles .action-remove', function(){
if (window.confirm("Are you sure you want to delete?")) {
var attachmentPath = $(this).attr("data-image");
var divID = $(this).parents(".base-image").attr("id");
var imageID = $(this).parents(".base-image").find(".hiddneattachID").val();
jQuery.ajax({
url: "<?php echo $this->getUrl(); ?>wallpaper/index/deleteCustomize?isAjax=true",
type: "POST",
data: {filename: attachmentPath, form_key: window.FORM_KEY, imageID:imageID},
showLoader: true,
success: function (response) {
if(response.success == true){
var parentElements = $(".base-image#"+divID).prev().children();
$(".base-image#"+divID).remove();
if($(".base-image").length > 0)
{
$('#mainImageSrc').attr("src",parentElements.find('.wallpaper-image').attr('src'));
parentElements.find('.selectImage').attr('checked','checked');
var srcFilename = parentElements.find('.selectImage').attr('data-srcfilename');
var srcType = parentElements.find('.selectImage').attr('data-srctype');
$('.action-bw').attr('data-image',srcFilename).attr('data-type',srcType);
$('.action-sepia').attr('data-image',srcFilename).attr('data-type',srcType);
$('.action-flip').attr('data-image',srcFilename).attr('data-type',srcType);
$('.action-cancel').attr('data-image',srcFilename).attr('data-type',srcType);
$('.action-apply').attr('data-image',srcFilename).attr('data-type',srcType);
}
else
{
$('#mainImageSrc').attr("src", "<?php echo $this->getUrl(); ?>10221276943_45e198c6c6_4k.jpg");
var srcFilename = '10221276943_45e198c6c6_4k.jpg';
var srcType = 'jpg';
$('.action-bw').attr('data-image',srcFilename).attr('data-type',srcType);
$('.action-sepia').attr('data-image',srcFilename).attr('data-type',srcType);
$('.action-flip').attr('data-image',srcFilename).attr('data-type',srcType);
$('.action-cancel').attr('data-image',srcFilename).attr('data-type',srcType);
$('.action-apply').attr('data-image',srcFilename).attr('data-type',srcType);
}
}
},
error: function (response) {
alert(response.message);
}
});
}
});
$(document).on('click', '.action-bw', function(){
var attachmentPath = $(this).attr("data-image");
$('.mainImage').addClass('mainImage-image-grayscale');
$('div.actions').hide();
$('div.actions-save').show();
$('.action-apply').attr('data-action', '1');
});
$(document).on('click', '.action-sepia', function(){
var attachmentPath = $(this).attr("data-image");
$('.mainImage').addClass('mainImage-image-sepia');
$('div.actions').hide();
$('div.actions-save').show();
$('.action-apply').attr('data-action', '2');
});
$(document).on('click', '.action-flip', function(){
var attachmentPath = $(this).attr("data-image");
$('.mainImage').addClass('mainImage-image-flip');
$('div.actions').hide();
$('div.actions-save').show();
$('.action-apply').attr('data-action', '3');
});
$(document).on('click', '.action-cancel', function(){
var attachmentPath = $(this).attr("data-image");
$('.mainImage').removeClass('mainImage-image-grayscale').removeClass('mainImage-image-sepia').removeClass('mainImage-image-flip');
$('div.actions').show();
$('div.actions-save').hide();
$('.action-apply').removeAttr('data-action');
});
$(document).on('change', "input[name='selectImage']", function(){
var srcPath = $(this).attr("data-src");
var srcType = $(this).attr("data-srctype");
var srcFilename = $(this).attr("data-srcfilename")
$('.action-bw').attr('data-image',srcFilename).attr('data-type',srcType);
$('.action-sepia').attr('data-image',srcFilename).attr('data-type',srcType);
$('.action-flip').attr('data-image',srcFilename).attr('data-type',srcType);
$('.action-cancel').attr('data-image',srcFilename).attr('data-type',srcType);
$('.action-apply').attr('data-image',srcFilename).attr('data-type',srcType);
$('#mainImageSrc').attr("src", srcPath);
});
$(document).on('click', '.action-apply', function(){
var imageName = $(this).attr("data-image");
var imageType = $(this).attr("data-type");
var imageAction = $(this).attr("data-action");
jQuery.ajax({
url: "<?php echo $this->getUrl(); ?>wallpaper/index/imageCustomize?isAjax=true",
type: "POST",
data: {filename: imageName, fileType:imageType, fileAction:imageAction},
showLoader: true,
success: function (response) {
if(response.error == false)
{
$('.action-bw').attr('data-image',response.data.filename).attr('data-type',response.data.fileType);
$('.action-sepia').attr('data-image',response.data.filename).attr('data-type',response.data.fileType);
$('.action-flip').attr('data-image',response.data.filename).attr('data-type',response.data.fileType);
$('.action-cancel').attr('data-image',response.data.filename).attr('data-type',response.data.fileType);
$('.action-apply').attr('data-image',response.data.filename).attr('data-type',response.data.fileType);
$('.mainImage').removeClass('mainImage-image-grayscale').removeClass('mainImage-image-sepia').removeClass('mainImage-image-flip');
$('div.actions').show();
$('div.actions-save').hide();
$('.action-apply').removeAttr('data-action');
$("#attachmentFiles").append(response.data.html);
$('#mainImageSrc').attr("src", response.data.path);
// Create dummy image to get real width and height
$("<img>").attr("src", response.data.path).load(function(){
var realWidth = this.width;
var realHeight = this.height;
var width = getSizeInCM(realWidth);
var height = getSizeInCM(realHeight);
/*alert("Original width=" + width + ", " + "Original height=" + height);*/
});
}
else
{
$('.mainImage').removeClass('mainImage-image-grayscale').removeClass('mainImage-image-sepia').removeClass('mainImage-image-flip');
$('div.actions').hide();
$('div.actions-save').show();
alert(response.message);
}
},
error: function (response) {
alert(response.message);
}
});
});
/**** Upload Image ****/
$('#uploadAttachment').click(function(e){e.preventDefault(); $('#attachment').trigger('click'); });
$("#attachment").change(function(){
var data = $("#frm_attachment").get(0);
jQuery.ajax({
url: "<?php echo $this->getUrl(); ?>wallpaper/index/addCustomize?isAjax=true' ?>",
type: "POST",
data: new FormData(data),
processData: false,
contentType: false,
showLoader: true,
success: function (response) {
if(response.error == false)
{
$('.action-bw').attr('data-image',response.data.filename).attr('data-type',response.data.fileType);
$('.action-sepia').attr('data-image',response.data.filename).attr('data-type',response.data.fileType);
$('.action-flip').attr('data-image',response.data.filename).attr('data-type',response.data.fileType);
$('.action-cancel').attr('data-image',response.data.filename).attr('data-type',response.data.fileType);
$('.action-apply').attr('data-image',response.data.filename).attr('data-type',response.data.fileType);
$('div.actions').show();
$("#attachmentFiles").append(response.data.html);
$('#mainImageSrc').attr("src", response.data.path);
$('#frm_attachment')[0].reset();
// Create dummy image to get real width and height
$("<img>").attr("src", response.data.path).load(function(){
var realWidth = this.width;
var realHeight = this.height;
var width = getSizeInCM(realWidth);
var height = getSizeInCM(realHeight);
/*alert("Original width=" + width + ", " + "Original height=" + height);*/
});
}
else
{
alert(response.message);
$('#frm_attachment')[0].reset();
}
},
error: function (response) {
alert(response.message);
$('#frm_attachment')[0].reset();
}
});
});
});
});
</script>
Step2: Create one “AddCustomize.php” file to upload an image.
<?php
namespace MagemonkeysWallpaperControllerIndex;
use MagentoFrameworkJsonHelperData as JsonHelper;
class AddCustomize extends MagentoFrameworkAppActionAction
{
protected $_pageFactory;
protected $connection;
protected $_mediaDirectory;
protected $_fileUploaderFactory;
public $_storeManager;
public function __construct(
MagentoFrameworkAppActionContext $context,
MagentoFrameworkAppResourceConnection $connection,
JsonHelper $jsonHelper,
MagentoFrameworkControllerResultJsonFactory $resultJsonFactory,
MagentoFrameworkFilesystem $filesystem,
MagentoMediaStorageModelFileUploaderFactory $fileUploaderFactory,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoFrameworkViewResultPageFactory $pageFactory)
{
$this->_pageFactory = $pageFactory;
$this->connection = $connection;
$this->jsonHelper = $jsonHelper;
$this->resultJsonFactory = $resultJsonFactory;
$this->_mediaDirectory = $filesystem->getDirectoryWrite(MagentoFrameworkAppFilesystemDirectoryList::MEDIA);
$this->_fileUploaderFactory = $fileUploaderFactory;
$this->_storeManager = $storeManager;
return parent::__construct($context);
}
public function execute(){
$_postData = $this->getRequest()->getPost();
$message = "";
$newFileName = "";
$error = false;
$data = array();
try{
$target = $this->_mediaDirectory->getAbsolutePath('wallpaper/');
//attachment is the input file name posted from your form
$uploader = $this->_fileUploaderFactory->create(['fileId' => 'attachment']);
$_fileType = $uploader->getFileExtension();
$uniqid = uniqid();
$newFileName = $uniqid .'.'. $_fileType;
/** Allowed extension types */
$uploader->setAllowedExtensions(['jpg', 'jpeg', 'png']);
/** rename file name if already exists */
$uploader->setAllowRenameFiles(true);
$result = $uploader->save($target, $newFileName); //Use this if you want to change your file name
//$result = $uploader->save($target);
if ($result['file']) {
$_mediaUrl = $this->_storeManager->getStore()->getBaseUrl(MagentoFrameworkUrlInterface::URL_TYPE_MEDIA);
$_src = $_mediaUrl.'wallpaper/'.$newFileName;
$error = false;
$message = __("File has been successfully uploaded");
$html = '<div class="image item base-image" data-role="image" id="'. $uniqid .'">
<div class="wallpaper-image-wrapper">
<div class="radioContainer">
<input data-src="'.$_src.'" data-srctype="'. $_fileType .'" data-srcfilename="'. $newFileName .'" checked="checked" class="selectImage selectImage-'. $uniqid .'" type="radio" name="selectImage" value="'. $uniqid .'" />
</div>
<div class="imageContainer">
<img class="wallpaper-image" data-role="image-element" src="'.$_src.'" alt="">
</div>
<div class="delete-action">
<button type="button" class="action-remove" data-role="delete-button" data-image="'.$newFileName.'" title="'. __('Delete image') .'"><span>'. __('Delete image') .'</span></button>
</div>
</div>
</div>';
$data = array('filename' => $newFileName, 'path' => $_mediaUrl.'wallpaper/'.$newFileName, 'fileType' => $_fileType, 'html' => $html);
}
} catch (Exception $e) {
$error = true;
$message = $e->getMessage();
}
$resultJson = $this->resultJsonFactory->create();
return $resultJson->setData([
'message' => $message,
'data' => $data,
'error' => $error
]);
}
}
Step3: Create one “DeleteCustomize.php” file to delete your uploaded image.
<?php
namespace MagemonkeysWallpaperControllerIndex;
use MagentoFrameworkJsonHelperData as JsonHelper;
class DeleteCustomize extends MagentoFrameworkAppActionAction
{
protected $_pageFactory;
protected $connection;
protected $_mediaDirectory;
protected $_fileUploaderFactory;
public $_storeManager;
protected $_file;
public function __construct(
MagentoFrameworkAppActionContext $context,
MagentoFrameworkAppResourceConnection $connection,
JsonHelper $jsonHelper,
MagentoFrameworkControllerResultJsonFactory $resultJsonFactory,
MagentoFrameworkFilesystem $filesystem,
MagentoMediaStorageModelFileUploaderFactory $fileUploaderFactory,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoFrameworkFilesystemDriverFile $file,
MagentoFrameworkViewResultPageFactory $pageFactory)
{
$this->_pageFactory = $pageFactory;
$this->connection = $connection;
$this->jsonHelper = $jsonHelper;
$this->resultJsonFactory = $resultJsonFactory;
$this->_mediaDirectory = $filesystem->getDirectoryWrite(MagentoFrameworkAppFilesystemDirectoryList::MEDIA);
$this->_fileUploaderFactory = $fileUploaderFactory;
$this->_storeManager = $storeManager;
$this->_file = $file;
return parent::__construct($context);
}
public function execute(){
$_postData = $this->getRequest()->getPost();
$message = "";
$newFileName = "";
$success = false;
$mediaRootDir = $this->_mediaDirectory->getAbsolutePath();
$_fileName = $mediaRootDir .'wallpaper/'. $_postData['filename'];
if ($this->_file->isExists($_fileName)) {
try{
/*$this->attachment->load($_postData['imageID']);
$this->attachment->delete();*/
$this->_file->deleteFile($_fileName);
$message = __('File removed successfully.');
$success = true;
} catch (Exception $ex) {
$message = $ex->getMessage();
$success = false;
}
}else{
$message = "File not found.";
$success = false;
}
$resultJson = $this->resultJsonFactory->create();
return $resultJson->setData([
'message' => $message,
'data' => '',
'success' => $success
]);
}
}
Step4: Create one “ImageCustomize.php” file to give the effects to your uploaded image. I have given some effect to an image as per my requirements.
<?php
namespace MagemonkeysWallpaperControllerIndex;
use MagentoFrameworkJsonHelperData as JsonHelper;
class ImageCustomize extends MagentoFrameworkAppActionAction
{
protected $_pageFactory;
protected $connection;
protected $_mediaDirectory;
protected $_rootDirectory;
protected $_fileUploaderFactory;
public $_storeManager;
protected $_file;
public function __construct(
MagentoFrameworkAppActionContext $context,
MagentoFrameworkAppResourceConnection $connection,
JsonHelper $jsonHelper,
MagentoFrameworkControllerResultJsonFactory $resultJsonFactory,
MagentoFrameworkFilesystem $filesystem,
MagentoMediaStorageModelFileUploaderFactory $fileUploaderFactory,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoFrameworkFilesystemDriverFile $file,
MagentoFrameworkViewResultPageFactory $pageFactory)
{
$this->_pageFactory = $pageFactory;
$this->connection = $connection;
$this->jsonHelper = $jsonHelper;
$this->resultJsonFactory = $resultJsonFactory;
$this->_mediaDirectory = $filesystem->getDirectoryWrite(MagentoFrameworkAppFilesystemDirectoryList::MEDIA);
$this->_rootDirectory = $filesystem->getDirectoryRead(MagentoFrameworkAppFilesystemDirectoryList::ROOT);
$this->_fileUploaderFactory = $fileUploaderFactory;
$this->_storeManager = $storeManager;
$this->_file = $file;
return parent::__construct($context);
}
public function execute(){
$_postData = $this->getRequest()->getPost();
$message = "";
$newFileName = "";
$error = false;
$data = array();
$uniqid = uniqid();
$mediaRootDir = $this->_mediaDirectory->getAbsolutePath();
$rootDirectory = $this->_rootDirectory->getAbsolutePath();
$_fileType = $_postData['fileType'];
$_fileAction = $_postData['fileAction'];
if($_postData['filename'] == '10221276943_45e198c6c6_4k.jpg')
{
$newFileName = $uniqid .'.'.$_fileType;
$filePath = $rootDirectory . $_postData['filename'];
$_fileName = $mediaRootDir .'wallpaper/'. $newFileName;
$newFullPathOfImage = $_fileName;
copy($filePath, $_fileName);
}
else
{
$_fileName = $mediaRootDir .'wallpaper/'. $_postData['filename'];
$newFullPathOfImage = $mediaRootDir .'wallpaper/'. $uniqid .'.'.$_fileType;
$newFileName = $uniqid .'.'.$_fileType;
}
if ($this->_file->isExists($_fileName)){
try{
if($_fileAction == 1) /*** Grayscale (Black & White) ***/
{
if(strtolower($_fileType) == 'jpg' || strtolower($_fileType) == 'jpeg')
{
$im = ImageCreateFromJpeg($_fileName);
$imgw = imagesx($im);
$imgh = imagesy($im);
for ($i=0; $i<$imgw; $i++)
{
for ($j=0; $j<$imgh; $j++)
{
// get the rgb value for current pixel
$rgb = ImageColorAt($im, $i, $j);
// extract each value for r, g, b
$rr = ($rgb >> 16) & 0xFF;
$gg = ($rgb >> 8) & 0xFF;
$bb = $rgb & 0xFF;
// get the Value from the RGB value
$g = round(($rr + $gg + $bb) / 3);
// grayscale values have r=g=b=g
$val = imagecolorallocate($im, $g, $g, $g);
// set the gray value
imagesetpixel ($im, $i, $j, $val);
}
}
imagejpeg($im, $newFullPathOfImage);
$message = __('Image converted to grayscale.');
imagedestroy($im);
}
else
{
$im = imagecreatefrompng($_fileName);
if($im && imagefilter($im, IMG_FILTER_GRAYSCALE))
{
$message = __('Image converted to grayscale.');
imagepng($im, $newFullPathOfImage);
imagedestroy($im);
}
else
{
$message = __('Conversion to grayscale failed.');
}
}
}
else if($_fileAction == 2) /*** Sepia Color Scale ***/
{
if(strtolower($_fileType) == 'jpg' || strtolower($_fileType) == 'jpeg')
{
// Load
$im = ImageCreateFromJpeg($_fileName);
imagefilter($im, IMG_FILTER_GRAYSCALE);
imagefilter($im,IMG_FILTER_BRIGHTNESS,-10);
imagefilter($im, IMG_FILTER_COLORIZE, 65, 50, 0);
// Output
imagejpeg($im, $newFullPathOfImage);
imagedestroy($im);
}
else
{
// Load
$im = imagecreatefrompng($_fileName);
imagefilter($im, IMG_FILTER_GRAYSCALE);
imagefilter($im,IMG_FILTER_BRIGHTNESS,-10);
imagefilter($im, IMG_FILTER_COLORIZE, 65, 50, 0);
// Output
imagepng($im, $newFullPathOfImage);
imagedestroy($im);
}
$message = __('Image converted to sepia.');
}
else if($_fileAction == 3) /*** Flip Image ***/
{
if(strtolower($_fileType) == 'jpg' || strtolower($_fileType) == 'jpeg')
{
// Load
$im = ImageCreateFromJpeg($_fileName);
// Flip it horizontally
imageflip($im, IMG_FLIP_HORIZONTAL);
// Output
imagejpeg($im, $newFullPathOfImage);
imagedestroy($im);
}
else
{
// Load
$im = imagecreatefrompng($_fileName);
// Flip it horizontally
imageflip($im, IMG_FLIP_HORIZONTAL);
// Output
imagepng($im, $newFullPathOfImage);
imagedestroy($im);
}
$message = __('Image flipped.');
}
$_mediaUrl = $this->_storeManager->getStore()->getBaseUrl(MagentoFrameworkUrlInterface::URL_TYPE_MEDIA);
$_src = $_mediaUrl.'wallpaper/'.$newFileName;
$message = __("File has been successfully uploaded");
$html = '<div class="image item base-image" data-role="image" id="'. $uniqid .'">
<div class="wallpaper-image-wrapper">
<div class="radioContainer">
<input data-src="'.$_src.'" data-srctype="'. $_fileType .'" data-srcfilename="'. $newFileName .'" checked="checked" class="selectImage selectImage-'. $uniqid .'" type="radio" name="selectImage" value="'. $uniqid .'" />
</div>
<div class="imageContainer">
<img class="wallpaper-image" data-role="image-element" src="'.$_src.'" alt="">
</div>
<div class="delete-action">
<button type="button" class="action-remove" data-role="delete-button" data-image="'.$newFileName.'" title="'. __('Delete image') .'"><span>'. __('Delete image') .'</span></button>
</div>
</div>
</div>';
$data = array('filename' => $newFileName, 'path' => $_mediaUrl.'wallpaper/'.$newFileName, 'fileType' => $_fileType, 'html' => $html);
$error = false;
}
catch (Exception $ex) {
$message = $ex->getMessage();
$error = true;
}
}else{
$message = __("File not found.");
$error = true;
}
$resultJson = $this->resultJsonFactory->create();
return $resultJson->setData([
'message' => $message,
'data' => $data,
'error' => $error
]);
}
}

