Javascript EXIF Image Orientation and Image Preview - javascript

I have a PHP file input and some javascript that displays a small preview of the image that has been selected for upload. My question is how do I read the EXIF data and display (in preview) the image in its correct orientation?
PHP file input
<div id="dropzone">
<div>Add Photo</div>
<?php echo elgg_view('input/file', array(
'name' => 'upload',
'accept' => 'image/jpeg, image/JPG, image/png',
)); ?>
</div>
Javascript
/* Find any element which has a 'data-onload' function and load that to simulate an onload. */ $('[data-onload]').each(function(){ eval($(this).data('onload')); });
$(function() {
$('#dropzone').on('dragover', function() {
$(this).addClass('hover');
});
$('#dropzone').on('dragleave', function() {
$(this).removeClass('hover');
});
$('#dropzone input').on('change', function(e) {
var file = this.files[0];
$('#dropzone').removeClass('hover');
if (this.accept && $.inArray(file.type, this.accept.split(/, ?/)) == -1) {
return alert('File type not allowed.');
}
$('#dropzone').addClass('dropped');
$('#dropzone img').remove();
if ((/^image\/(gif|png|jpeg|JPG)$/i).test(file.type)) {
var reader = new FileReader(file);
reader.readAsDataURL(file);
reader.onload = function(e) {
var data = e.target.result,
$img = $('<img />').attr('src', data).fadeIn();
$('#dropzone div').html($img);
};
} else {
var ext = file.name.split('.').pop();
$('#dropzone div').html(ext);
}
});
});

You can write your own algorithm of exif parse, or use one of existing js libs, for example exif-js
fileToImage function(file, callback){
if(!file || !(/^image\/(gif|png|jpeg|jpg)$/i).test(file.type)){
callback(null);
return;
};
// for modern browsers and ie from 10
var createObjectURL = (window.URL || window.webkitURL || {}).createObjectURL || null;
var image = new Image();
image.onload = function(){
// exif only for jpeg
if(/^image\/(jpeg|jpg)$/i).test(file.type)){
var convertExifOrienationToAngle = function (orientation) {
var exifDegrees = [
0, // 0 - not used
0, // 1 - The 0th row is at the visual top of the image, and the 0th column is the visual left-hand side.
0, // 2 - The 0th row is at the visual top of the image, and the 0th column is the visual right-hand side.
180, // 3 - The 0th row is at the visual bottom of the image, and the 0th column is the visual right-hand side.
0, // 4 - The 0th row is at the visual bottom of the image, and the 0th column is the visual left-hand side.
0, // 5 - The 0th row is the visual left-hand side of the image, and the 0th column is the visual top.
90, // 6 - The 0th row is the visual right-hand side of the image, and the 0th column is the visual top.
0, // 7 - The 0th row is the visual right-hand side of the image, and the 0th column is the visual bottom.
270 // 8 - The 0th row is the visual left-hand side of the image, and the 0th column is the visual bottom.
];
if (orientation > 0 && orientation < 9 && exifDegrees[orientation] != 0) {
return exifDegrees[orientation];
} else {
return 0;
}
};
EXIF.getData(image, function() {
var angle = convertExifOrienationToAngle(EXIF.getTag(image, "Orientation") || 0);
var style = "-moz-transform: rotate(" + angle + "deg);-ms-transform: rotate(" + angle + "deg);-webkit-transform: rotate(" + angle + "deg);-o-transform: rotate(" + angle + "deg);transform: rotate(" + angle + "deg);";
image.setAttribute("style", style);
callback(image);
});
}else{
callback(image);
}
};
image.onerror = image.onabort = function(){
callback(null);
};
if(createObjectURL){
image.src = createObjectURL(file);
}else{
var reader = new FileReader(file);
reader.onload = function(e) {
image.src = e.target.result
};
reader.onerror = reader.onerror = function(){
callback(null);
};
reader.readAsDataURL(file);
} }
Example of use:
fileToImage(file,function(image){
if(image != null){
document.body.appendChild(image)
}else{
alert("can't load image");
}
});
also you can use method from this post get orientation without lib

Related

How to detect, that drawing a canvas object is finished?

I have following JS code (found here, on stackoverflow, and a little-bit modded), which resize image on client side using canvas.
function FileListItem(a) {
// Necesary to proper-work of CatchFile function (especially image-resizing).
// Code by Jimmy Wärting (https://github.com/jimmywarting)
a = [].slice.call(Array.isArray(a) ? a : arguments)
for (var c, b = c = a.length, d = !0; b-- && d;) d = a[b] instanceof File
if (!d) throw new TypeError('expected argument to FileList is File or array of File objects')
for (b = (new ClipboardEvent('')).clipboardData || new DataTransfer; c--;) b.items.add(a[c])
return b.files
}
function CatchFile(obj) {
// Based on ResizeImage function.
// Original code by Jimmy Wärting (https://github.com/jimmywarting)
var file = obj.files[0];
// Check that file is image (regex)
var imageReg = /[\/.](gif|jpg|jpeg|tiff|png|bmp)$/i;
if (!file) return
var uploadButtonsDiv = document.getElementById('upload_buttons_area');
// Check, that it is first uploaded file, or not
// If first, draw a div for showing status
var uploadStatusDiv = document.getElementById('upload_status_area');
if (!uploadStatusDiv) {
var uploadStatusDiv = document.createElement('div');
uploadStatusDiv.setAttribute('class', 'upload-status-area');
uploadStatusDiv.setAttribute('id', 'upload_status_area');
uploadButtonsDiv.parentNode.insertBefore(uploadStatusDiv, uploadButtonsDiv.nextSibling);
// Draw sub-div for each input field
var i;
for (i = 0; i < 3; i++) {
var uploadStatus = document.createElement('div');
uploadStatus.setAttribute('class', 'upload-status');
uploadStatus.setAttribute('id', ('upload_status_id_commentfile_set-' + i + '-file'));
uploadStatusDiv.append(uploadStatus);
}
}
var canvasDiv = document.getElementById('canvas-area');
var currField = document.getElementById(obj.id);
var currFieldLabel = document.getElementById(('label_' + obj.id));
// Main image-converting procedure
if (imageReg.test(file.name)) {
file.image().then(img => {
const canvas = document.createElement('canvas')
canvas.setAttribute('id', ('canvas_' + obj.id));
const ctx = canvas.getContext('2d')
const maxWidth = 1600
const maxHeight = 1200
// Calculate new size
const ratio = Math.min(maxWidth / img.width, maxHeight / img.height)
const width = img.width * ratio + .5|0
const height = img.height * ratio + .5|0
// Resize the canvas to the new dimensions
canvas.width = width
canvas.height = height
// Drawing canvas-object is necessary to proper-work
// on mobile browsers.
// In this case, canvas is inserted to hidden div (display: none)
ctx.drawImage(img, 0, 0, width, height)
canvasDiv.appendChild(canvas)
// Get the binary (aka blob)
canvas.toBlob(blob => {
const resizedFile = new File([blob], file.name, file)
const fileList = new FileListItem(resizedFile)
// Temporary remove event listener since
// assigning a new filelist to the input
// will trigger a new change event...
obj.onchange = null
obj.files = fileList
obj.onchange = CatchFile
}, 'image/jpeg', 0.70)
}
)
// If file is image, during conversion show status
function ShowConvertConfirmation() {
if (document.getElementById('canvas_' + obj.id)) {
document.getElementById(('upload_status_' + obj.id)).innerHTML =
'<font color="#4CAF50">Konwertowanie pliku ' + file.name + ' zakończone!</font>';
return true;
}
else {
document.getElementById(('upload_status_' + obj.id)).innerHTML =
'<font color="#4CAF50">Konwertowanie pliku ' + file.name + ' zakończone!</font>';
return false;
}
}
// Loop ShowConvertConfirmation function untill return true (file is converted)
var convertConfirmationLoop = setInterval(function() {
var isConfirmed = ShowConvertConfirmation();
if (!isConfirmed) {
ShowConvertConfirmation();
}
else {
// Break loop
clearInterval(convertConfirmationLoop);
}
}, 2000); // Check every 2000ms
}
// If file is not an image, show status with filename
else {
document.getElementById(('upload_status_' + obj.id)).innerHTML =
'<font color="#4CAF50">Dodano plik ' + file.name + '</font>';
//uploadStatusDiv.append(uploadStatus);
}
}
Canvas is drawn in hidden div:
<div id="canvas-area" style="overflow: hidden; height: 0;"></div>
I am only detect, that div canvas-area is presented and basing on this, JS append another div with status.
Unfortunatelly on some mobile devices (mid-range smartphones), message will be showed before finish of drawing (it is wrong). Due to this, some uploaded images are corrupted or stay in original size.
How to prevent this?
Everything that should happen after the image has loaded, should be executed within the then callback, or called from within it.
It is important to realise that the code that is not within that callback will execute immediately, well before the drawing has completed.

Photoshop javascript batch replace smart layer from folder and resize

I am trying to work out how to use javascript with photoshop, but eventhough i dont find a logical error in the code, it doesnt work properly.
I have a folder of 1000+ images/.ai files that have varying dimensions. I need these images on the Pillow and saved as .jpeg.
I choose the smartlayer and run the script to choose the images and it saves them correctly. The only problem is, that the resizing of images and positioning dont work properly.
If i put the image in manually, it works without issues, but not with the script.
If the width is greater than the height, it should set the width to 1200 px and calculate the height according to that. (and vice versa) and place in the middle of the layer.
How do i fix the resizing and positioning?
Is it possible to choose a folder where the images are inside instead of selecting the images?
How do i handle it when there are 2 smart layers to change in the mockup instead of 1?
Anyone know where the problem lies this code?
Im grateful for any bit of help!
// Replace SmartObject’s Content and Save as JPG
// 2017, use it at your own risk
// Via #Circle B: https://graphicdesign.stackexchange.com/questions/92796/replacing-a-smart-object-in-bulk-with-photoshops-variable-data-or-scripts/93359
// JPG code from here: https://forums.adobe.com/thread/737789
#target photoshop
if (app.documents.length > 0) {
var myDocument = app.activeDocument;
var theName = myDocument.name.match(/(.*)\.[^\.]+$/)[1];
var thePath = myDocument.path;
var theLayer = myDocument.activeLayer;
// JPG Options;
jpgSaveOptions = new JPEGSaveOptions();
jpgSaveOptions.embedColorProfile = true;
jpgSaveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
jpgSaveOptions.matte = MatteType.NONE;
jpgSaveOptions.quality = 8;
// Check if layer is SmartObject;
if (theLayer.kind != "LayerKind.SMARTOBJECT") {
alert("selected layer is not a smart object")
} else {
// Select Files;
if ($.os.search(/windows/i) != -1) {
var theFiles = File.openDialog("please select files", "*.psd;*.tif;*.jpg;*.ai", true)
} else {
var theFiles = File.openDialog("please select files", getFiles, true)
};
};
(function (){
var startRulerUnits = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;
var bounds = activeDocument.activeLayer.bounds;
var height = bounds[3].value - bounds[1].value;
var width = bounds[2].value - bounds[0].value;
if (height > width){
var newSize1 = (100 / width) * 800;
activeDocument.activeLayer.resize(newSize1, newSize1, AnchorPosition.MIDDLECENTER);
app.preferences.rulerUnits = startRulerUnits;
}
else{
var newSize2 = (100 / height) * 800;
activeDocument.activeLayer.resize(newSize2, newSize2, AnchorPosition.MIDDLECENTER);
app.preferences.rulerUnits = startRulerUnits;
}
})();
if (theFiles) {
for (var m = 0; m < theFiles.length; m++) {
// Replace SmartObject
theLayer = replaceContents(theFiles[m], theLayer);
var theNewName = theFiles[m].name.match(/(.*)\.[^\.]+$/)[1];
// Save JPG
myDocument.saveAs((new File(thePath + "/" + theName + "_" + theNewName + ".jpg")), jpgSaveOptions, true,Extension.LOWERCASE);
}
}
};
// Get PSDs, TIFs and JPGs from files
function getFiles(theFile) {
if (theFile.name.match(/\.(psd|tif|jpg)$/i) != null || theFile.constructor.name == "Folder") {
return true
}
};
// Replace SmartObject Contents
function replaceContents(newFile, theSO) {
app.activeDocument.activeLayer = theSO;
// =======================================================
var idplacedLayerReplaceContents = stringIDToTypeID("placedLayerReplaceContents");
var desc3 = new ActionDescriptor();
var idnull = charIDToTypeID("null");
desc3.putPath(idnull, new File(newFile));
var idPgNm = charIDToTypeID("PgNm");
desc3.putInteger(idPgNm, 1);
executeAction(idplacedLayerReplaceContents, desc3, DialogModes.NO);
return app.activeDocument.activeLayer
};
I have attached 2 pictures. 1 how it needs to look like and 2 what the script outputs
Correct
Wrong
Your replaced images have to be the same resolution as the smart object.
You can declare the folder path in your code. If you still want to select the path by hand, you can select one image in the path, and extract the parent folder path.
You can recursively go through all of the layers in the documents and extract all the smart objects that you want to replace.
You may want a function to recursively traverse all the layers in the document
function browseLayer(layer, fn) {
if (layer.length) {
for (var i = 0; i < layer.length; ++i) {
browseLayer(layer[i], fn)
}
return;
}
if (layer.layers) {
for (var j = 0; j < layer.layers.length; ++j) {
browseLayer(layer.layers[j], fn);
}
return;
}
//apply this function for every layer
fn(layer)
}
Get all the smart objects in the document
const smartObjects = [];
//The smart objects can be visit twice or more
//use this object to mark the visiting status
const docNameIndex = {};
const doc = app.open(new File("/path/to/psd/file"));
browseLayer(doc.layers, function (layer) {
//You cannot replace smart object with position is locked
if (layer.kind == LayerKind.SMARTOBJECT && layer.positionLocked == false) {
smartLayers.push(layer);
doc.activeLayer = layer;
//open the smart object
executeAction(stringIDToTypeID("placedLayerEditContents"), new ActionDescriptor(), DialogModes.NO);
//activeDocument is now the smart object
const docName = app.activeDocument.name;
if (!docNameIndex[docName]) {
docNameIndex[docName] = true;
smartObjects.push({
id: layer.id,
name: layer.name,
docName: docName,
width : app.activeDocument.width.as('pixels'),
height : app.activeDocument.height.as('pixels'),
resolution : app.activeDocument.resolution //important
});
}
//reactive the main document
app.activeDocument = doc;
}
});
I assume that you have two smart objects needed to replace, the images for replacement are stored in different folders with the same name.
smartObjects[0].replaceFolderPath = "/path/to/folder/1";
smartObjects[1].replaceFolderPath = "/path/to/folder/2";
//we need temp folder to store the resize images
smartObjects[0].tempFolderPath = "/path/to/temp/folder/1";
smartObjects[1].tempFolderPath = "/path/to/temp/folder/2";
Ex: The first iteration will replace smartObjects[0] with "/path/to/folder/1/image1.jpg", and smartObjects[1] with "/path/to/folder/image1.jpg"
Now resize all the images following the properties of the smart objects
smartObjects.forEach(function(smartObject){
//Get all files in the folder
var files = new Folder(smartObject.replaceFolderPath).getFiles();
//Resize all the image files
files.forEach(function (file) {
var doc = app.open(file);
doc.resizeImage(
new UnitValue(smartObject.width + ' pixels'),
new UnitValue(smartObject.height + ' pixels'),
smartObject.resolution
);
//save to temp folder
doc.saveAs(
new File(smartObject.tempFolderPath + "/" + file.name),
new PNGSaveOptions(),
true
);
doc.close(SaveOptions.DONOTSAVECHANGES)
});
});
Finally, replace the smart object
//get list of file again
var files = new Folder(smartObject.replaceFolderPath).getFiles();
files.forEach(function(file){
var fileName = file.name;
smartObjects.forEach(function(smartObject){
//active the window opening the smart object
app.activeDocument = app.documents.getByName(args.documentName);
var desc = new ActionDescriptor();
desc.putPath(charIDToTypeID("null"), new File(smartObject.tempFolderPath + "/" + fileName));
executeAction(stringIDToTypeID( "placedLayerReplaceContents" ), desc, DialogModes.NO);
});
//Now export document
var webOptions = new ExportOptionsSaveForWeb();
webOptions.format = SaveDocumentType.PNG; // SaveDocumentType.JPEG
webOptions.optimized = true;
webOptions.quality = 100;
doc.exportDocument(new File("/path/to/result/folder" + file.name), ExportType.SAVEFORWEB, webOptions);
});
Now you can close all the opening smart objects
smartObjects.forEach(function (s) {
app.documents.getByName(r.docName).close(SaveOptions.DONOTSAVECHANGES);
});

Jquery validating - comparing the content of jquery variables

I am writing a script which allows users to up load image files. Each user has an account to login and when they do so a data table is read and returns a list of screens associated to their account.
The user selects a screen and a jQuery script returns the screen resolution.
var w;
var h;
$(document).ready(function()
{
$('#board').change(function(){
$.get('check_override_image.php', { RecordID: form2.board.value },
function(result) {
result = JSON.parse(result);
w = result["imagesizes"][0]["DisplayWidth"];
h = result["imagesizes"][0]["DisplayHeight"];
$('#size').html("Display width: " + result["imagesizes"][0]["DisplayWidth"]
+ ",<br> Display height: " + result["imagesizes"][0]["DisplayHeight"]).show();
if (result["imagesizes"][0]["DisplayType"] == 'P' ) {
$("#portrait").show();
$("#landscape").hide();
$("#SelectView").show();
$("#SelectViewText").show();
} else {
$("#landscape").show();
$("#portrait").hide();
$("#SelectView").show();
$("#SelectViewText").show();
}
});
});
});
The user clicks on a "Browse" link to select an image from their local drive and another jQuery script returns the image filename and the image dimensions.
$(document).ready(function(){
//LOCAL IMAGE
var _URL = window.URL || window.webkitURL;
$("#image_field").change(function (e) {
var file, img;
if ((file = this.files[0])) {
img = new Image();
img.onload = function () {
if ( this.width != w || this.height != y) {
alert(this.width + " " + this.height);
};
};
img.src = _URL.createObjectURL(file);
}
});
});
My question: is there a way I can use the result["imagesizes"][0]["DisplayWidth"]and result["imagesizes"][0]["DisplayHeight"] along with "this.width" and "this.height" to make sure the the selected image dimensions are the same as the selected screen resolution?
I worked out how this is done and updated my question code to reflect

upload fails with image greater than 800kb

I have a form where i can drag and drop an image into a canvas and then click an upload button to upload the file to the server. Below is my javascript file and php file. I cannot find where or why this will not allow me to upload something greater than 800kb? I believe its all failing in the php at if(file_put_contents($uploaddir.$randomName, $decodedData)) { but again i dont know why? The sql statment fails to by the way thats why i think its failing at that point in the php file. 32M is php max file size upload.
UPDATE... i removed anything to do with uploading with php in the php and only left echo $randomName.":uploaded successfully"; which now leads me to believe there is something wrong in the JS file at $.post('/mods/photogallery/manager/upload.php?gpID=' + bla, dataArray[index], function(data) { for anything greater than 800kb (ish)
JS
$(document).ready(function() {
// Makes sure the dataTransfer information is sent when we
// Drop the item in the drop box.
jQuery.event.props.push('dataTransfer');
var z = -40;
// The number of images to display
var maxFiles = 1;
var errMessage = 0;
// Get all of the data URIs and put them in an array
var dataArray = [];
// Bind the drop event to the dropzone.
$('#drop-files').bind('drop', function(e) {
// Stop the default action, which is to redirect the page
// To the dropped file
var files = e.dataTransfer.files;
// Show the upload holder
$('#uploaded-holder').show();
$('#drop-files').hide();
// For each file
$.each(files, function(index, file) {
// Some error messaging
if (!files[index].type.match('image.*')) {
if(errMessage == 0) {
$('#drop-files').html('Hey! Images only');
++errMessage
}
else if(errMessage == 1) {
$('#drop-files').html('Stop it! Images only!');
++errMessage
}
else if(errMessage == 2) {
$('#drop-files').html("Can't you read?! Images only!");
++errMessage
}
else if(errMessage == 3) {
$('#drop-files').html("Fine! Keep dropping non-images.");
errMessage = 0;
}
return false;
}
// Check length of the total image elements
if($('#dropped-files > .image').length < maxFiles) {
// Change position of the upload button so it is centered
var imageWidths = ((220 + (40 * $('#dropped-files > .image').length)) / 2) - 20;
$('#upload-button').css({'left' : imageWidths+'px', 'display' : 'block'});
}
// Start a new instance of FileReader
var fileReader = new FileReader();
// When the filereader loads initiate a function
fileReader.onload = (function(file) {
return function(e) {
// Push the data URI into an array
dataArray.push({name : file.name, value : this.result});
// Move each image 40 more pixels across
z = z+40;
var image = this.result;
// Just some grammatical adjustments
if(dataArray.length == 1) {
$('#upload-button span').html("1 file to be uploaded");
} else {
$('#upload-button span').html(dataArray.length+" files to be uploaded");
}
// Place extra files in a list
if($('#dropped-files > .image').length < maxFiles) {
// Place the image inside the dropzone
$('#dropped-files').append('<div class="image" style="background: #fff url('+image+') no-repeat;background-size: cover;background-position: center center;"> </div>');
}
else {
$('#extra-files .number').html('+'+($('#file-list li').length + 1));
// Show the extra files dialogue
$('#extra-files').show();
// Start adding the file name to the file list
$('#extra-files #file-list ul').append('<li>'+file.name+'</li>');
}
};
})(files[index]);
// For data URI purposes
fileReader.readAsDataURL(file);
});
});
function restartFiles() {
// This is to set the loading bar back to its default state
$('#loading-bar .loading-color').css({'width' : '0%'});
$('#loading').css({'display' : 'none'});
$('#loading-content').html(' ');
// --------------------------------------------------------
// We need to remove all the images and li elements as
// appropriate. We'll also make the upload button disappear
$('#upload-button').hide();
$('#dropped-files > .image').remove();
$('#extra-files #file-list li').remove();
$('#extra-files').hide();
$('#uploaded-holder').hide();
$('#drop-files').show();
// And finally, empty the array/set z to -40
dataArray.length = 0;
z = -40;
return false;
}
$('#upload-button .upload').click(function() {
$("#loading").show();
var totalPercent = 100 / dataArray.length;
var x = 0;
var y = 0;
$('#loading-content').html('Uploading '+dataArray[0].name);
$.each(dataArray, function(index, file) {
bla = $('#gpID').val();
$.post('/mods/photogallery/manager/upload.php?gpID=' + bla, dataArray[index], function(data) {
var fileName = dataArray[index].name;
++x;
// Change the bar to represent how much has loaded
$('#loading-bar .loading-color').css({'width' : totalPercent*(x)+'%'});
if(totalPercent*(x) == 100) {
// Show the upload is complete
$('#loading-content').html('Uploading Complete!');
// Reset everything when the loading is completed
setTimeout(restartFiles, 500);
} else if(totalPercent*(x) < 100) {
// Show that the files are uploading
$('#loading-content').html('Uploading '+fileName);
}
// Show a message showing the file URL.
var dataSplit = data.split(':');
if(dataSplit[1] == 'uploaded successfully') {
alert('Upload Was Successfull');
var realData = '<li>'+fileName+' '+dataSplit[1]+'</li>';
$('#drop-files').css({
'background' :'url(/mods/photogallery/photos/' + dataSplit[0] + ') no-repeat',
'background-size': 'cover',
'background-position' : 'center center'
});
$('#uploaded-files').append('<li>'+fileName+' '+dataSplit[1]+'</li>');
// Add things to local storage
if(window.localStorage.length == 0) {
y = 0;
} else {
y = window.localStorage.length;
}
window.localStorage.setItem(y, realData);
} else {
$('#uploaded-files').append('<li><a href="/mods/photogallery/photos/'+data+'. File Name: '+dataArray[index].name+'</li>');
}
});
});
return false;
});
// Just some styling for the drop file container.
$('#drop-files').bind('dragenter', function() {
$(this).css({'box-shadow' : 'inset 0px 0px 20px rgba(0, 0, 0, 0.1)', 'border' : '4px dashed #bb2b2b'});
return false;
});
$('#drop-files').bind('drop', function() {
$(this).css({'box-shadow' : 'none', 'border' : '4px dashed rgba(0,0,0,0.2)'});
return false;
});
// For the file list
$('#extra-files .number').toggle(function() {
$('#file-list').show();
}, function() {
$('#file-list').hide();
});
$('#dropped-files #upload-button .delete').click(restartFiles);
// Append the localstorage the the uploaded files section
if(window.localStorage.length > 0) {
$('#uploaded-files').show();
for (var t = 0; t < window.localStorage.length; t++) {
var key = window.localStorage.key(t);
var value = window.localStorage[key];
// Append the list items
if(value != undefined || value != '') {
$('#uploaded-files').append(value);
}
}
} else {
$('#uploaded-files').hide();
}
});
PHP
// We're putting all our files in a directory.
$uploaddir = '../photos/';
// The posted data, for reference
$file = $_POST['value'];
$name = $_POST['name'];
$gpID = $_GET['gpID'];
// Get the mime
$getMime = explode('.', $name);
$mime = end($getMime);
// Separate out the data
$data = explode(',', $file);
// Encode it correctly
$encodedData = str_replace(' ','+',$data[1]);
$decodedData = base64_decode($encodedData);
// You can use the name given, or create a random name.
// We will create a random name!
$randomName = $gpID.'.'.$mime;
if(file_put_contents($uploaddir.$randomName, $decodedData)) {
$sql = "UPDATE zmods_galleriesphotos SET gpFile = '$randomName' WHERE gpID = '$gpID'";
$rows = $db->query($sql);
echo $randomName.":uploaded successfully";
}
else {
echo "Something went wrong. Check that the file isn't corrupted";
}
Check the upload_max_filesize in your php.ini file (although it should be large enough by default)
Check the post_max_size as well
If you're uploading multiple files, then also check max_file_uploads
The fact that your sql is failing makes me wonder if this is a mysql problem and not a php problem. What is the SQL error that occurs?

Kineticjs Object Handling & Event Listener

I sell custom equipment and on my site, I have a flash tool where customers can assign colors to glove parts and see what it will look like.
I've been working on a HTML5 version of this tool, so the iPad crowd can do the same thing. Click here for what I've done,
I took kineticjs multiple picture loader and hacked it to load all the pics necessary to stage and the color buttons, which are multiple instances of the same image. In their example, it was only 2 images, so they var name each image, which were manipulative. My goal is to dynamically create variable, based on image name.
I'm using a for loop and if statements to position the parts according to their type. If the image being loaded is a button, the original instance is not added to the stage, but another for loop, with a counter, creates instances and put on the stage. The variable is part string+n (wht0). From here I initiate an eventlistener, when clicked is suppose to hide all glove parts pertaining to the option and show the appropriate color. That code I have already in my AS.
I created an eventlistener on the white buttons (first button) that when clicked, I set it to hide one of the white leather part of glove. But when I click the button, I get the error in console that the glove part (ex wlt_wht), I get an error stating that the object is not defined. But when the image was loaded the variable name came from the current array object being loaded.
I added another variable before the callback call, to convert the content of the array to a string and used the document.write to confirm that the object name is correct, but after creating the object its now [object object]. In flash, you manually assign the movie clip name and target.name is available if you call it.
How can I write the Image obj so I can control the object? In the doc there is a reference for id and name as properties of the object, but when I set these, it did not work with me. Sure, I could have manually created each Kinetic.Image(), but there's no fun in that.. especially with 191 images. Any tip on how I can get around this problem?
Checkout http://jsfiddle.net/jacobsultd/b2BwU/6/ to examine and test script.
function loadImages(sources, callback) {
var assetDir = 'http://dev.nystixs.com/test/inf/';
var fileExt = '.png';
var images = {};
var loadedImages = 0;
var numImages = 0;
for (var src in sources) {
numImages++;
}
for (var src in sources) {
images[src] = new Image();
images[src].onload = function () {
var db = sources[src].toString();
var dbname = db.slice(-0, -4);
if (++loadedImages >= numImages) {
callback(images, dbname);
}
};
images[src].src = assetDir + sources[src];
//images[src].src = assetDir+sources[src]+".png";
}
}
function initStage(images, db) {
var shapesLayer = new Kinetic.Layer();
var messageLayer = new Kinetic.Layer();
//Loading Images
var xpos = 0;
var ypos = 200;
for (var i in images) {
var glvP = i.slice(0, 3);
db = new Kinetic.Image({
image: images[i],
x: xpos,
y: ypos
});
if (glvP == "wlt") {
shapesLayer.add(db);
db.setPosition(186.95, 7.00);
//db.hide();
shapesLayer.draw();
} else if (glvP == "lin") {
shapesLayer.add(db);
db.setPosition(204.95, 205.00);
} else if (glvP == "plm") {
shapesLayer.add(db);
db.setPosition(311.95, 6.00);
} else if (glvP == "web") {
shapesLayer.add(db);
db.setPosition(315.95, 7.00);
} else if (glvP == "lce") {
shapesLayer.add(db);
db.setPosition(162.95, 3.00);
} else if (glvP == "thb") {
shapesLayer.add(db);
db.setPosition(63.00, 28.60);
} else if (glvP == "bfg") {
shapesLayer.add(db);
db.setPosition(167.95, 7.00);
} else if (glvP == "wst") {
shapesLayer.add(db);
db.setPosition(208.95, 234.00);
} else if (glvP == "fpd") {
shapesLayer.add(db);
db.setPosition(252.95, 82.00);
} else if (glvP == "bac") {
shapesLayer.add(db);
db.setPosition(0, 0);
} else if (glvP == "bnd") {
shapesLayer.add(db);
db.setPosition(196.95, 164.00);
} else {}
var rect = new Kinetic.Rect({
x: 710,
y: 6,
stroke: '#555',
strokeWidth: 5,
fill: '#ddd',
width: 200,
height: 325,
shadowColor: 'white',
shadowBlur: 10,
shadowOffset: [5, 5],
shadowOpacity: 0.2,
cornerRadius: 10
});
shapesLayer.add(rect);
// End of Glove Parts Tabs
//Load Color Buttons
if (glvP == "wht") {
xpos = -5.00;
bpos = 375;
var zpos = -5.00;
var tpos = -5.00;
db.setPosition(xpos, bpos);
//shapesLayer.add(db);
var n = 0;
for (n = 0; n < 12; n++) {
if (n < 4) {
var glvB = "wht" + n;
var btn = glvB;
glvB = new Kinetic.Image({
image: images[i],
width: 18,
height: 18,
id: 'wht0'
});
glvB.on('mouseout', function () {
blankText('');
});
glvB.on('mouseover', function () {
writeColors('White', btn);
});
glvB.on('click', function () {
console.log(glvB + " clicked");
wht.hide();
shapesLayer.draw();
});
glvB.setPosition((xpos + 20), bpos);
shapesLayer.add(glvB);
xpos = (xpos + 230);
}
You can use your .png image filenames to automate your color-button coding efforts.
No need to manually code 10 glove components X 21 colors per component (210 color buttons).
Assume you’ve split the each image URL (filename) to get the color and glove-type.
Then you can create all 210 color buttons with one piece of reusable code.
Demo: http://jsfiddle.net/m1erickson/H5FDc/
Example Code:
// Usage:
addColorButton(100,100,"red","fingers");
// 1 function to add 210 color-buttons
function addColorButton(x,y,color,component){
// create this button
var button=new Kinetic.Image({
x:x,
y:y,
image: imageArray[ color+"-color-button" ],
});
// save the color as a property on this button
button.gloveColor=color;
// save the glove component name as a property on this button
button.gloveComponent=component; // eg, "fingers"
// resuable click handler
// Will change the gloves "#fingers" to "red-fingers-image"
button.on("click",function(){
// eg. get the image "red-fingers-image"
var newImage = imageArray[this.gloveColor+"-"+this.gloveComponent+"-image"];
// eg. get the Kinetic.Image with id:”finger”
var glovePart = layer.find("#"+this.gloveComponent”][0];
// change the Kinetic id:finger’s image
// to the red-fingers-image
glovePart.setImage(newImage);
layer.draw();
});
layer.add(button);
}

Categories

Resources