AngularJS file upload from ngThumb directive (with angular-file-upload) - php

I am using Angular-File-Upload to upload file to server. Everything works fine and the file can be saved in DB.
The question is, how can I load back the images that I saved when in edit mode?
This is the directive to create canvas when upload the pic
'use strict';
myApp
.directive('ngThumb', ['$window', function($window) {
var helper = {
support: !!($window.FileReader && $window.CanvasRenderingContext2D),
isFile: function(item) {
return angular.isObject(item) && item instanceof $window.File;
},
isImage: function(file) {
var type = '|' + file.type.slice(file.type.lastIndexOf('/') + 1) + '|';
return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
}
};
return {
restrict: 'A',
template: '<canvas/>',
link: function(scope, element, attributes) {
if (!helper.support) return;
var params = scope.$eval(attributes.ngThumb);
if (!helper.isFile(params.file)) return;
if (!helper.isImage(params.file)) return;
var canvas = element.find('canvas');
var reader = new FileReader();
reader.onload = onLoadFile;
reader.readAsDataURL(params.file);
function onLoadFile(event) {
var img = new Image();
img.onload = onLoadImage;
img.src = event.target.result;
}
function onLoadImage() {
var width = params.width || this.width / this.height * params.height;
var height = params.height || this.height / this.width * params.width;
canvas.attr({ width: width, height: height });
canvas[0].getContext('2d').drawImage(this, 0, 0, width, height);
}
}
};
}]);
This is an html snippet that load canvas when there is an upload:
<div class="table-responsive" ng-hide="!uploaderImages.queue.length">
<table class="table">
<thead>
<tr>
<th width="50%">Name</th>
<th ng-show="uploaderImages.isHTML5">Size</th>
<th ng-show="uploaderImages.isHTML5">Progress</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in uploaderImages.queue">
<td><strong>{{ item.file.name }}</strong>
<div ng-show="uploaderImages.isHTML5" ng-thumb="{ file: item._file, height: 100 }"></div>
</td>
<td ng-show="uploaderImages.isHTML5" nowrap>{{ item.file.size/1024/1024|number:2 }} MB</td>
<td ng-show="uploaderImages.isHTML5">
<div class="progress progress-xs margin-bottom-0">
<div class="progress-bar" role="progressbar" ng-style="{ 'width': item.progress + '%' }"></div>
</div></td>
<td class="text-center">
<span ng-show="item.isSuccess"><i class="glyphicon glyphicon-ok"></i></span>
<span ng-show="item.isCancel"><i class="glyphicon glyphicon-ban-circle"></i></span>
<span ng-show="item.isError"><i class="glyphicon glyphicon-remove"></i></span>
</td>
<td nowrap>
<button type="button" class="btn btn-danger btn-xs" ng-click="item.remove()">
<span class="glyphicon glyphicon-trash"></span> Remove
</button></td>
</tr>
</tbody>
</table>
</div>
Thanks!!

Since the uploader is working fine already and you're able to save the images into the database, all you need to do is to show the uploaded images as thumbnails on a canvas.
That can be done using some jQuery like this:
// source of a large image - replace this with the URL of the uploaded image (served from the database)
var IMAGE_SRC = "http://cdn-media-1.lifehack.org/wp-content/files/2014/09/activities-on-the-beach.jpg";
// set the height for the thumbnail - your uploader currently has 100
var height = 100;
function drawImage() {
// create a new Image object
var img = new Image();
// set up the onLoad handler on the image object to draw the thumbnail into the canvas
img.onload = function() {
// calculate the thumbnail width for the fixed height above, respecting the image aspect ratio
var width = this.width / this.height * height;
// set the dimensions on the canvas
$("canvas").attr({
width: width,
height: height
});
// draw the image from the loaded image object
$("canvas")[0].getContext("2d").drawImage(img, 0, 0, width, height);
};
// set the source of the image object to the URL of the uploaded image (served from the database)
img.src = IMAGE_SRC;
}
// Do all of this when the button is clicked
$("button").click(drawImage);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Load image into Canvas</button>
<br />
<br />
<canvas></canvas>
The same code could also be converted into another angular directive - something like <uploaded-image></uploaded-image>.

Writing down a simple directive to preview the returned images is quite easy. More or less is the a simplified version of the ngThumb directive you have provided.
angular.module('components', [])
.directive('imgPreview', [function () {
return {
restrict: 'E',
template: '<canvas/>',
replace: true,
link: function (scope, element, attrs) {
var myCanvas = element[0];
var ctx = myCanvas.getContext('2d');
var img = new Image;
img.onerror = function () {
throw new Error("Image can't be loaded");
}
img.onload = function () {
myCanvas.width = img.width;
myCanvas.height = img.height;
ctx.drawImage(img, 0, 0); // Or at whatever offset you like
};
img.src = attrs.image;
}
}
}]);
Demo

// source of a large image - replace this with the URL of the uploaded image (served from the database)
var IMAGE_SRC = "http://cdn-media-1.lifehack.org/wp-content/files/2014/09/activities-on-the-beach.jpg";
// set the height for the thumbnail - your uploader currently has 100
var height = 100;
function drawImage() {
// create a new Image object
var img = new Image();
// set up the onLoad handler on the image object to draw the thumbnail into the canvas
img.onload = function() {
// calculate the thumbnail width for the fixed height above, respecting the image aspect ratio
var width = this.width / this.height * height;
// set the dimensions on the canvas
$("canvas").attr({
width: width,
height: height
});
// draw the image from the loaded image object
$("canvas")[0].getContext("2d").drawImage(img, 0, 0, width, height);
};
// set the source of the image object to the URL of the uploaded image (served from the database)
img.src = IMAGE_SRC;
}
// Do all of this when the button is clicked
$("button").click(drawImage);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Load image into Canvas</button>
<br />
<br />
<canvas></canvas>

If I understand your question right, then I think you need to upload a blob (so after editing an image in canvas you have a Data URI. And you need to convert this into a Blob which you can upload!
Here is the solution I used for uploading a cropped image with angular-file-upload:
https://github.com/nervgh/angular-file-upload/issues/208#issuecomment-116344239
You need to use
uploader.onBeforeUploadItem
to overwrite the actual file = item._file!
PS: There is also a function for converting 'DataURI' to 'Blob' in the given link!

Related

the image remains the same after being updated and uploaded with new images

I have uploaded the image and crop it with croppie, the image successfully updates the database and successfully enters the directory.
but the new image overwrites the old image with the same name, it was intentionally done. but the image displayed again by php remains the old image (the image has been overwritten with the new one)
Initially there was no problem but when I didn't open the project for more than 2 week there was a problem like the one above
HTML tag
<div class="col-sm-3">
<h4>Profile Picture</h4>
<hr>
<form action="" id="form" method="post">
<label class="cabinet center-block">
<figure><img src="" class="gambar img-responsive img-thumbnail" id="item-img-output" />
<figcaption><i class="fa fa-camera"></i></figcaption>
</figure>
<input type="file" class="item-img file center-block" name="file_photo"/>
</label>
</form>
</div>
JS with CROPPIE
<script type="text/javascript">
// Start upload preview image
$(".gambar").attr("src", "../profile/pictures/img/<?=$profile['profile']?>");
var $uploadCrop,
tempFilename,
rawImg,
imageId;
function readFile(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('.upload-demo').addClass('ready');
$('#cropImagePop').modal('show');
rawImg = e.target.result;
}
reader.readAsDataURL(input.files[0]);
}
else {
swal("Desculpe, seu navegador não suporta o FileReader API.");
}
}
$uploadCrop = $('#upload-demo').croppie({
viewport: {
width: 230,
height: 230,
},
enforceBoundary: false,
enableExif: true
});
$('#cropImagePop').on('shown.bs.modal', function(){
// alert('Shown pop');
$uploadCrop.croppie('bind', {
url: rawImg
}).then(function(){
console.log('jQuery bind complete');
});
});
$('.item-img').on('change', function () { imageId = $(this).data('id'); tempFilename = $(this).val();
$('#cancelCropBtn').data('id', imageId); readFile(this); });
$('#cropImageBtn').on('click', function (ev) {
$uploadCrop.croppie('result', {
type: 'base64',
format: 'jpeg',
size: {width: 270, height: 270}
}).then(function (resp) {
$('#item-img-output').attr('src', resp);
//$('#cropImagePop').modal('hide');
$.ajax({
url: "../lib/proses/upload.php",
type: "POST",
data: {"image":resp},
success: function (data) {
html = '<img src="' + resp + '" />';
$("#upload-image-i").html(html);
$('#cropImagePop').modal('hide');
swal.fire(
'Berhasil !',
'Profile berhasil diubah',
'success'
)
}
});
$('#cropImagePop').modal('hide');
});
});
// End upload preview image
</script>
Upload Process
<?php
session_start();
require "../koneksi.php";
$username = $_SESSION['username'];
$croped_image = $_POST['image'];
list($type, $croped_image) = explode(';', $croped_image);
list(, $croped_image) = explode(',', $croped_image);
$croped_image = base64_decode($croped_image);
$image_name = $username.'.png';
// insert name to database
$sql = "UPDATE users SET profile = '$image_name' WHERE username = '$username'";
$query = mysqli_query($conn, $sql);
// upload cropped image to server
file_put_contents('../../profile/pictures/img/'.$image_name, $croped_image);
?>
I want the newly uploaded image to appear to replace the old image in
the file that displays the image (ex. index file, etc.)
Have you checked your browser cache? Maybe try adding a random param to image path, like myimage.jpg?c=[randomNumber], this will force the browser to download the image again.
Clear your cache, are you using a PHP framework?

PHP Image Compression Before Upload [duplicate]

I need to provide a means for a user to upload photos to their web site in jpeg format. However, the photos are very large in original size, and I would like to make the resize before upload option very effortless for the user. It seems my only options are a client side application that resizes the photos before uploading them via a web service, or a client side JavaScript hook on the upload operation that resizes the images. The second option is very tentative because I don't have a JavaScript image resizing library, and it will be difficult to get the JavaScript to run my current resize tool, ImageMagick.
I'm sure this is not too uncommon a scenario, and some suggestions or pointers to sites that do this will be appreciated.
In 2011, we can know do it with the File API, and canvas.
This works for now only in firefox and chrome.
Here is an example :
var file = YOUR_FILE,
fileType = file.type,
reader = new FileReader();
reader.onloadend = function() {
var image = new Image();
image.src = reader.result;
image.onload = function() {
var maxWidth = 960,
maxHeight = 960,
imageWidth = image.width,
imageHeight = image.height;
if (imageWidth > imageHeight) {
if (imageWidth > maxWidth) {
imageHeight *= maxWidth / imageWidth;
imageWidth = maxWidth;
}
}
else {
if (imageHeight > maxHeight) {
imageWidth *= maxHeight / imageHeight;
imageHeight = maxHeight;
}
}
var canvas = document.createElement('canvas');
canvas.width = imageWidth;
canvas.height = imageHeight;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0, imageWidth, imageHeight);
// The resized file ready for upload
var finalFile = canvas.toDataURL(fileType);
}
}
reader.readAsDataURL(file);
There is multiple-technology-capable Plupload tool which declares that it can do resizing before upload, but I haven't tried it yet. I have also find a suitable answer in my question about binary image handling javascript libs.
You have several options:
Java
ActiveX (only on windows)
Silverlight
Flash
Flex
Google Gears (the most recent version is capable of resizing and drag and drop from your desktop)
I've done a lot of research looking for a similar solution to what you have described and there a lot of solutions out there that vary a lot in quality and flexibility.
My suggestion is find a solution which will do 80% of what you need and customize it to suit your needs.
I think you need Java or ActiveX for that. For example Thin Image Upload
What jao and russau say is true. The reason being is JavaScript does not have access to the local filesystem due to security reasons. If JavaScript could "see" your image files, it could see any file, and that is dangerous.
You need an application-level control to be able to do this, and that means Flash, Java or Active-X.
Unfortunately you won't be able to resize the images in Javascript. It is possible in Silverlight 2 tho.
If you want to buy something already done: Aurigma Image Uploader is pretty impressive - $USD250 for the ActiveX and Java versions. There's some demos on the site, I'm pretty sure facebook use the same control.
Here some modifications to feed tensorflow.js(soo fast with it!!) with resized and cropped image (256x256px), plus showing original image under cropped image, to see what is cut off.
$("#image-selector").change(function(){
var file = $("#image-selector").prop('files')[0];
var maxSize = 256; // well now its minsize
var reader = new FileReader();
var image = new Image();
var canvas = document.createElement('canvas');
var canvas2 = document.createElement('canvas');
var dataURItoBlob = function (dataURI) {
var bytes = dataURI.split(',')[0].indexOf('base64') >= 0 ?
atob(dataURI.split(',')[1]) :
unescape(dataURI.split(',')[1]);
var mime = dataURI.split(',')[0].split(':')[1].split(';')[0];
var max = bytes.length;
var ia = new Uint8Array(max);
for (var i = 0; i < max; i++)
ia[i] = bytes.charCodeAt(i);
return new Blob([ia], { type: mime });
};
var resize = function () {
var width = image.width;
var height = image.height;
if (width > height) {
if (width > maxSize) {
width *= maxSize / height;
height = maxSize;
}
} else {
if (height > maxSize) {
height *= maxSize / width;
width = maxSize;
}
}
if (width==height) { width = 256; height = 256; }
var posiw = 0;
var posih = 0;
if (width > height) {posiw = (width-height)/2; }
if (height > width) {posih = ((height - width) / 2);}
canvas.width = 256;
canvas.height = 256;
canvas2.width = width;
canvas2.height = height;
console.log('iw:'+image.width+' ih:'+image.height+' w:'+width+' h:'+height+' posiw:'+posiw+' posih:'+posih);
canvas.getContext('2d').drawImage(image, (-1)*posiw, (-1)*posih, width, height);
canvas2.getContext('2d').drawImage(image, 0, 0, width, height);
var dataUrl = canvas.toDataURL('image/jpeg');
var dataUrl2 = canvas2.toDataURL('image/jpeg');
if ($("#selected-image").attr("src")) {
$("#imgspeicher").append('<div style="width:100%; border-radius: 5px; background-color: #eee; margin-top:10px;"><div style="position: relative; margin:10px auto;"><img id="selected-image6" src="'+$("#selected-image").attr("src")+'" style="margin: '+document.getElementById('selected-image').style.margin+';position: absolute; z-index: 999;" width="" height=""><img id="selected-image2" src="'+$("#selected-image2").attr("src")+'" style="margin: 10px; opacity: 0.4;"></div><div class="row" style="margin:10px auto; text-align: left;"> <ol>'+$("#prediction-list").html()+'</ol> </div></div>');
}
$("#selected-image").attr("src",dataUrl);
$("#selected-image").width(256);
$("#selected-image").height(256);
$("#selected-image").css('margin-top',posih+10+'px');
$("#selected-image").css('margin-left',posiw+10+'px');
$("#selected-image2").attr("src",dataUrl2);
$("#prediction-list").empty();
console.log("Image was loaded, resized and cropped");
return dataURItoBlob(dataUrl);
};
return new Promise(function (ok, no) {
reader.onload = function (readerEvent) {
image.onload = function () { return ok(resize()); };
image.src = readerEvent.target.result;
};
let file = $("#image-selector").prop('files')[0];
reader.readAsDataURL(file);});});
Html implementation:
<input id ="image-selector" class="form-control border-0" type="file">
<div style="position: relative; margin:10px auto; width:100%;" id="imgnow">
<img id="selected-image" src="" style="margin: 10px; position: absolute; z-index: 999;">
<img id="selected-image2" src="" style="margin: 10px; opacity: 0.4;">
</div>
Also not resize to a maximum width/height, but to minimum. We get a 256x256px square image.
Pure JavaScript solution. My code resizes JPEG by bilinear interpolation, and it doesn't lose exif.
https://github.com/hMatoba/JavaScript-MinifyJpegAsync
function post(data) {
var req = new XMLHttpRequest();
req.open("POST", "/jpeg", false);
req.setRequestHeader('Content-Type', 'image/jpeg');
req.send(data.buffer);
}
function handleFileSelect(evt) {
var files = evt.target.files;
for (var i = 0, f; f = files[i]; i++){
var reader = new FileReader();
reader.onloadend = function(e){
MinifyJpegAsync.minify(e.target.result, 1280, post);
};
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
You can resize the image in the client-side before uploading it using an image processing framework.
Below I used MarvinJ to create a runnable code based on the example in the following page:
"Processing images in client-side before uploading it to a server"
Basically I use the method Marvin.scale(...) to resize the image. Then, I upload the image as a blob (using the method image.toBlob()). The server answers back providing a URL of the received image.
/***********************************************
* GLOBAL VARS
**********************************************/
var image = new MarvinImage();
/***********************************************
* FILE CHOOSER AND UPLOAD
**********************************************/
$('#fileUpload').change(function (event) {
form = new FormData();
form.append('name', event.target.files[0].name);
reader = new FileReader();
reader.readAsDataURL(event.target.files[0]);
reader.onload = function(){
image.load(reader.result, imageLoaded);
};
});
function resizeAndSendToServer(){
$("#divServerResponse").html("uploading...");
$.ajax({
method: 'POST',
url: 'https://www.marvinj.org/backoffice/imageUpload.php',
data: form,
enctype: 'multipart/form-data',
contentType: false,
processData: false,
success: function (resp) {
$("#divServerResponse").html("SERVER RESPONSE (NEW IMAGE):<br/><img src='"+resp+"' style='max-width:400px'></img>");
},
error: function (data) {
console.log("error:"+error);
console.log(data);
},
});
};
/***********************************************
* IMAGE MANIPULATION
**********************************************/
function imageLoaded(){
Marvin.scale(image.clone(), image, 120);
form.append("blob", image.toBlob());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.marvinj.org/releases/marvinj-0.8.js"></script>
<form id="form" action='/backoffice/imageUpload.php' style='margin:auto;' method='post' enctype='multipart/form-data'>
<input type='file' id='fileUpload' class='upload' name='userfile'/>
</form><br/>
<button type="button" onclick="resizeAndSendToServer()">Resize and Send to Server</button><br/><br/>
<div id="divServerResponse">
</div>

get jquery image width and add class

I'm having trouble getting the dimensions of a series of images that are loading via PHP.
<?
$Ldir="imgs/liveGallery/"; // Directory where files are stored
if ($Lhandle = opendir($Ldir)) {
while (false !== ($Lfile = readdir($Lhandle))) {
if ($Lfile != "." && $Lfile != "..") $Lthefiles[] = $Lfile;
}
closedir($Lhandle);
}
sort($Lthefiles);
for ($Li=0;$Li<count($Lthefiles);$Li++) { ?>
<a href="<?php echo $Ldir.$Lthefiles[$Li]; ?>" class="ilightbox">
<div class="adj">
<img src="<?php echo $Ldir.$Lthefiles[$Li]; ?>" class="percent">
</div>
</a>
<?php }
?>
In the above code PHP is doing its job loading all the images from a nearby directory. The .adj class is formatting the <div> into a square and floating them all to the left so they tile the screen. It's also hiding the overflow so that no matter the dimensions all you see is a square.
My issue comes when trying to read the widths and heights of the images that are being loaded into that <div>. I want to have the image fit at a width or height of 100% depending on which is proportional to fill the square. Here's the jquery code I thought should work.
$(window).load(function() {
$(".adj").each(function() {
var $this = $(this);
var imageWidth = $this.children("img").attr("width");
var imageHeight = $this.children("img").attr("height");
if (imageWidth < imageHeight){
$this.addClass("aW");
} else if (imageWidth > imageHeight) {
$this.addClass("aH");
}
});
});
I don't seem to be capturing an image width or height at all, with what I wrote above.
I'm using fullpage.js and ilightbox.js which may be messing with my code, but I doubt it. I've also tried putting a modified version of this code inside the PHP for loop (without the jquery each function) and that doesn't work either. HELP!
Here's a link for you.
You can try somethig like
$(window).load(function() {
$(".adj").each(function () {
var $this = $(this);
var img = new Image();
//Set Image source
img.src = $this.children("img").attr("src");
//Wait for image to be loaded.
//Event will fire when image is loaded
img.onload = function () {
//Get Height and width
var imageWidth = img.width;
var imageHeight = img.height;
if (imageWidth < imageHeight) {
$this.addClass("aW");
} else if (imageWidth > imageHeight) {
$this.addClass("aH");
}
};
});
});
Note: I am not sure, this is a best practice
You have set the width and height in the css styling and not inline as attributes,
So attributes width and height are empty
$this.children("img").attr("width"); // .attr would not work
Should be
$this.children("img").css("width"); // .css is the method
And
$(window).load(function() {
$(".adj").each(function() {
var $this = $(this);
// when your referring same img multiple times, grab it in a variable
var image = $this.children("img");
var imgWidth = image.width(); // or image.css("width")
var imageHeight = image.height(); // or image.css("height")
if (imageWidth < imageHeight){
$this.addClass("aW");
} else if (imageWidth > imageHeight) {
$this.addClass("aH");
}
});
});
note .css() gives in the px'.
Example 100px even though you set the values in pt or em etc. After seeing your code since your comparing the values I would suggest .width() and .height() as they return integer values and easy to compare
jQuery documentation
Note that .width() will always return the content width, regardless of the value of the CSS box-sizing property. As of jQuery 1.8, this may require retrieving the CSS width plus box-sizing property and then subtracting any potential border and padding on each element when the element has box-sizing: border-box. To avoid this penalty, use .css( "width" ) rather than .width()

Upload image after choosing filter

he i have here a script where users can choose a filder, but how can i make it when they are done with choosing a filder that the script sends the picture to a php script so that i can upload on the server?
$(function() {
/*
In this code, we are going to do the following:
1. Accept an image on drag and drop
2. Create a new canvas element (original), with a max size
of 500x500px (customizable) and keep it in memory
3. Listen for clicks on the filters. When one is selected:
3.1 Create a clone of the original canvas
3.2 Remove any canvas elements currently on the page
3.3 Append the clone to the #photo div
3.4 If the selected filter is different from the "Normal"
one, call the Caman library. Otherwise do nothing.
3.5 Mark the selected filter with the "active" class
4. Trigger the "Normal" filter
*/
var maxWidth = 500,
maxHeight = 500,
photo = $('#photo'),
originalCanvas = null,
filters = $('#filters li a'),
filterContainer = $('#filterContainer');
// Use the fileReader plugin to listen for
// file drag and drop on the photo div:
photo.fileReaderJS({
on:{
load: function(e, file){
// An image has been dropped.
var img = $('<img>').appendTo(photo),
imgWidth, newWidth,
imgHeight, newHeight,
ratio;
// Remove canvas elements left on the page
// from previous image drag/drops.
photo.find('canvas').remove();
filters.removeClass('active');
// When the image is loaded successfully,
// we can find out its width/height:
img.load(function() {
imgWidth = this.width;
imgHeight = this.height;
// Calculate the new image dimensions, so they fit
// inside the maxWidth x maxHeight bounding box
if (imgWidth >= maxWidth || imgHeight >= maxHeight) {
// The image is too large,
// resize it to fit a 500x500 square!
if (imgWidth > imgHeight) {
// Wide
ratio = imgWidth / maxWidth;
newWidth = maxWidth;
newHeight = imgHeight / ratio;
} else {
// Tall or square
ratio = imgHeight / maxHeight;
newHeight = maxHeight;
newWidth = imgWidth / ratio;
}
} else {
newHeight = imgHeight;
newWidth = imgWidth;
}
// Create the original canvas.
originalCanvas = $('<canvas>');
var originalContext = originalCanvas[0].getContext('2d');
// Set the attributes for centering the canvas
originalCanvas.attr({
width: newWidth,
height: newHeight
}).css({
marginTop: -newHeight/2,
marginLeft: -newWidth/2
});
// Draw the dropped image to the canvas
// with the new dimensions
originalContext.drawImage(this, 0, 0, newWidth, newHeight);
// We don't need this any more
img.remove();
filterContainer.fadeIn();
// Trigger the default "normal" filter
filters.first().click();
});
// Set the src of the img, which will
// trigger the load event when done:
img.attr('src', e.target.result);
},
beforestart: function(file){
// Accept only images.
// Returning false will reject the file.
return /^image/.test(file.type);
}
}
});
// Listen for clicks on the filters
filters.click(function(e){
e.preventDefault();
var f = $(this);
if(f.is('.active')){
// Apply filters only once
return false;
}
filters.removeClass('active');
f.addClass('active');
// Clone the canvas
var clone = originalCanvas.clone();
// Clone the image stored in the canvas as well
clone[0].getContext('2d').drawImage(originalCanvas[0],0,0);
// Add the clone to the page and trigger
// the Caman library on it
photo.find('canvas').remove().end().append(clone);
var effect = $.trim(f[0].id);
Caman(clone[0], function () {
// If such an effect exists, use it:
if( effect in this){
this[effect]();
this.render();
// Show the download button
showDownload(clone[0]);
}
else{
hideDownload();
}
});
});
// Use the mousewheel plugin to scroll
// scroll the div more intuitively
filterContainer.find('ul').on('mousewheel',function(e, delta){
this.scrollLeft -= (delta * 50);
e.preventDefault();
});
var downloadImage = $('a.downloadImage');
function showDownload(canvas){
downloadImage.off('click').click(function(){
// When the download link is clicked, get the
// DataURL of the image and set it as href:
var url = canvas.toDataURL("image/png;base64;");
downloadImage.attr('href', url);
}).fadeIn();
}
function hideDownload(){
downloadImage.fadeOut();
}
});
Try this...
HTML5 Drag and Drop Uploader - http://demo.tutorialzine.com/2011/09/html5-file-upload-jquery-php/

jquery image animation pops back to original size

I have a small problem. i have a link and when i click on this link i want an image to grow to a certain size and move to a certain spot on the screen. Everthing goes fine except that the image pops back to it's original size after the animation is complete.
My project is in Magento so sorry about the weird display of the image
PS: In the img tag it says width="235" height="401".
But the image pops to width=924" and height="1379". These are the dimensions of the actual image.
Here is my HTML code:
<a class="lightbox"href="#">pic</a>
<p class="product-image">
<?php
$_img = '<img id="image1" src="'.$this->helper('catalog/image')->init($_product, 'image').'" alt="'.$this->htmlEscape($this->getImageLabel()).'" title="'.$this->htmlEscape($this->getImageLabel()).'" width="235" height="401 " />';
echo $_helper->productAttribute($_product, $_img, 'image');
?>
And here is my jQuery code:
(function(window, $, undefined) {
jQuery(function(){
$('.lightbox').click(function(e) {
$('body').css('overflow-y', 'hidden'); // hide scrollbars!
var clicked = $('.lightbox').position();
$('<div id="overlay"></div>')
.css('top', $(document).scrollTop())
.css('opacity', '0')
.animate({'opacity': '0.5'}, 'slow')
.appendTo('body');
$('<div id="lightbox"></div>')
.hide()
.appendTo('body');
var img = new Image();
img.onload = function() {
var width = img.width,
height = img.height;
$('<img />')
.attr('src', img.src)
.load(function() {
positionLightboxImage(e, width, height);
})
.click(function() {
removeLightbox();
})
.appendTo('#lightbox');
};
img.src = $('#image1').attr('src');
/*var height = $('<img />').attr('width', .width());
alert(height);
$('<img />')
.attr('src', $(this).attr('href'))
.load(function() {
positionLightboxImage(e);
})
.click(function() {
removeLightbox();
})
.appendTo('#lightbox');
return false;*/
e.preventDefault();
});
});
function positionLightboxImage(e, width, height) {
var top = e.pageY - (height / 2);
var left = e.pageX - (width / 2);
$('#lightbox')
.css({
'top': top,
'left': left
})
.fadeIn(1)
.animate({'width': '50px'}, 3000);
}
function removeLightbox() {
$('#overlay, #lightbox')
.fadeOut('slow', function() {
$(this).remove();
$('body').css('overflow-y', 'auto'); // show scrollbars!
});
}
jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", Math.max(0, (($(window).height() - this.outerHeight()) / 2) +
$(window).scrollTop()) + "px");
this.css("left", Math.max(0, (($(window).width() - this.outerWidth()) / 2) +
$(window).scrollLeft()) + "px");
return this;
}
})(window, jQuery);
I hope i gave enough information. :)
For anyone who is interested in this answer.
It isn't the best way to fix this.
But using a smaller image for the lightbox and keeping the big image in the data-src did the trick for this situation.

Categories