upload fails with image greater than 800kb - javascript

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?

Related

How to get JS variable value on one page passed back to another page in PHP

I currently have two pages coded in php one page is called upload.php and the other page is called processing.php.
in the processing.php I currently have some Javascript that is ran it’s purpose is to check a log file for a video encoding progress to get the percentage left. this variable is called “progress” (This works fine when using console.log on the processing.php and I can see the incrementing percentage) I need to be able to get this value back to my upload.php page so that I can dynamically update a progress bar with its current value.
I already have one part of the puzzle working and that's to show a progress bar of the file uploading.
I have included some of the JS code on my upload.php and the JS code using in the processing.php page.
One thing that I tried was to have the JS variable inserted into a PHP session variable on the processing.php page, then echo this session variable out on the upload.php.
I have included in my code snippets below my attempt at using sessions.
Upload.php
<?php session_start();?>
<?php
$formProvider = new VideoDetailsFormProvider($con);
echo $formProvider->createUploadForm();
?>
</div>
<script>
$("form").submit(function() {
$("#loadingModal").modal("show");
var $el = $("#loadingModal");
$form = $(this);
uploadVideo($form, $el);
});
function uploadVideo($form, $el){
var formdata = new FormData($form[0]); //formelement
var ajax= new XMLHttpRequest();
ajax.upload.addEventListener("progress", function(event){
var percent = Math.round(event.loaded /event.total) * 100;
$el.find('#progressBarUpload').width(percent+'%').html(percent+'%');
//console.log(percent);
});
//progress completed load event
ajax.addEventListener("load", function(event){
$el.find('#progressBarUpload').addClass('progress-bar bg-success').html('Upload completed...');
});
ajax.addEventListener("error", function(event){
$el.find('#status').innerhtml = "Upload Failed";
});
ajax.addEventListener("abort", function(event){
$el.find('#status').innerhtml = "Upload Aborted";
});
ajax.open("POST", "processing.php");
ajax.send(formdata);
}
Please wait. This might take a while.
<?php echo($_SESSION['convertProgress']);?>
<div class="progress">
<div id="progressBarUpload" class="progress-bar" role="progressbar" style="width: 0%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
</div>
Processing.php
<?php session_start();
$convertProgressTest = $_SESSION['convertProgress'];
?>
<script>
var _progress = function(i){
i++;
// THIS MUST BE THE PATH OF THE .txt FILE SPECIFIED IN [1] :
var logfile = 'uploads/videos/logs/output.txt';
/* (example requires dojo) */
$.post(logfile).then( function(content){
// AJAX success
var duration = 0, time = 0, progress = 0;
var resArr = [];
// get duration of source
var matches = (content) ? content.match(/Duration: (.*?), start:/) : [];
if( matches.length>0 ){
var rawDuration = matches[1];
// convert rawDuration from 00:00:00.00 to seconds.
var ar = rawDuration.split(":").reverse();
duration = parseFloat(ar[0]);
if (ar[1]) duration += parseInt(ar[1]) * 60;
if (ar[2]) duration += parseInt(ar[2]) * 60 * 60;
// get the time
matches = content.match(/time=(.*?) bitrate/g);
console.log( matches );
if( matches.length>0 ){
var rawTime = matches.pop();
// needed if there is more than one match
if ($.isArray(rawTime)){
rawTime = rawTime.pop().replace('time=','').replace(' bitrate','');
} else {
rawTime = rawTime.replace('time=','').replace(' bitrate','');
}
// convert rawTime from 00:00:00.00 to seconds.
ar = rawTime.split(":").reverse();
time = parseFloat(ar[0]);
if (ar[1]) time += parseInt(ar[1]) * 60;
if (ar[2]) time += parseInt(ar[2]) * 60 * 60;
//calculate the progress
progress = Math.round((time/duration) * 100);
}
resArr['status'] = 200;
resArr['duration'] = duration;
resArr['current'] = time;
resArr['progress'] = progress;
console.log(resArr);
/* UPDATE YOUR PROGRESSBAR HERE with above values ... */
/* $("#progressBarconvert").width(progress+'%').html(progress+'%');
if(progress==100){
$("#progressBarconvert").addClass('progress-bar bg-success').html('Conversion Completed...');
}*/
var convertProgress = progress;
if(progress==0 && i>20){
//TODO err - giving up after 8 sec. no progress - handle progress errors here
console.log('{"status":-400, "error":"there is no progress while we tried to encode the video" }');
return;
} else if(progress<100){
setTimeout(function(){ _progress(i); }, 400);
}
} else if( content.indexOf('Permission denied') > -1) {
// TODO - err - ffmpeg is not executable ...
console.log('{"status":-400, "error":"ffmpeg : Permission denied, either for ffmpeg or upload location ..." }');
}
},
function(err){
// AJAX error
if(i<20){
// retry
setTimeout(function(){ _progress(0); }, 400);
} else {
console.log('{"status":-400, "error":"there is no progress while we tried to encode the video" }');
console.log( err );
}
return;
});
}
setTimeout(function(){ _progress(0); }, 800);
</script>
Since you dont want to leave upload.php you have to add return false; right after uploadVideo($form, $el);
Otherwise you trigger the upload asynchronously and go to progress.php synchronously(which means you leave upload.php)
You have 3 responsibilities here, so you could do it with 3 files:
upload.php - display the upload form
convert.php - do the conversion
progress.php - get the progress
In your convert.php you will need to add the line $_SESSION['convertProgress'] = convertProgress;
In your upload.php you can update your progressbar now by:
$.ajax('progress.php', function(content) {
// set element value etc...
});
As soon as you start the upload the File gets uploaded and converted by convert.php asynchronously. You can now trigger a JS-Timer, which does the above call to progress.php over and over until it reaches 100.
If you want to be able to do some errorhandling you can use JSON to pass more data back to your upload.php which calls progress.php.
PHP (example):
json_encode([
'progress' => 0,
'message' => '',
]);
JS decode:
JSON.parse(<content of progress.php>)
I have managed to resolve this now it's not pretty and it may not be the best way but it works for me, using #Pilan advice and help this is my workaround.
have 3 pages
The Update.php Page, The Processing.php Page and convertProgress.php, the convertProgress.php Page contains the the Javascript code mentioned at the beginning of my post. The upload.php contains the following.
var testing;
function beginUpload() {
$.ajax({
url: 'convertProgress.php',
type: 'POST',
//async: false,
data: {},
success: function (response) { //we got the response
if(response.progress){
testing = response.progress
console.log(testing);
}else {
beginUpload();
getProgress();
}
//var testing = response.progress;
},
error: function (jqxhr, status, exception) {
alert('Exception:', exception);
}
});
//console.log(testing);
}
Upload.php also has the same javascript code as the convertProgress.php
<script>
function getProgress() {
var _progress = function (i) {
i++;
// THIS MUST BE THE PATH OF THE .txt FILE SPECIFIED IN [1] :
var logfile = 'uploads/videos/logs/output.txt';
/* (example requires dojo) */
$.post(logfile).then(function (content) {
// AJAX success
var duration = 0, time = 0, progress = 0;
var resArr = [];
// get duration of source
var matches = (content) ? content.match(/Duration: (.*?), start:/) : [];
if (matches.length > 0) {
var rawDuration = matches[1];
// convert rawDuration from 00:00:00.00 to seconds.
var ar = rawDuration.split(":").reverse();
duration = parseFloat(ar[0]);
if (ar[1]) duration += parseInt(ar[1]) * 60;
if (ar[2]) duration += parseInt(ar[2]) * 60 * 60;
// get the time
matches = content.match(/time=(.*?) bitrate/g);
console.log(matches);
if (matches.length > 0) {
var rawTime = matches.pop();
// needed if there is more than one match
if ($.isArray(rawTime)) {
rawTime = rawTime.pop().replace('time=', '').replace(' bitrate', '');
} else {
rawTime = rawTime.replace('time=', '').replace(' bitrate', '');
}
// convert rawTime from 00:00:00.00 to seconds.
ar = rawTime.split(":").reverse();
time = parseFloat(ar[0]);
if (ar[1]) time += parseInt(ar[1]) * 60;
if (ar[2]) time += parseInt(ar[2]) * 60 * 60;
//calculate the progress
progress = Math.round((time / duration) * 100);
}
resArr['status'] = 200;
resArr['duration'] = duration;
resArr['current'] = time;
resArr['progress'] = progress;
console.log(resArr);
/* UPDATE YOUR PROGRESSBAR HERE with above values ... */
$("#progressBarconvert").width(progress+'%').html(progress+'%');
if(progress==100){
$("#progressBarconvert").addClass('progress-bar bg-success').html('Conversion Completed...');
}
if (progress == 0 && i > 20) {
//TODO err - giving up after 8 sec. no progress - handle progress errors here
console.log('{"status":-400, "error":"there is no progress while we tried to encode the video" }');
return;
} else if (progress < 100) {
setTimeout(function () {
_progress(i);
}, 400);
}
} else if (content.indexOf('Permission denied') > -1) {
// TODO - err - ffmpeg is not executable ...
console.log('{"status":-400, "error":"ffmpeg : Permission denied, either for ffmpeg or upload location ..." }');
}
},
function (err) {
// AJAX error
if (i < 20) {
// retry
setTimeout(function () {
_progress(0);
}, 400);
} else {
console.log('{"status":-400, "error":"there is no progress while we tried to encode the video" }');
console.log(err);
}
return;
});
}
setTimeout(function () {
_progress(0);
}, 800);
}
</script>
It's not pretty but it works for me. I hope this helps anyone that would like to get the conversion Progress from FFMPEG and populate a bootstrap Progress bar

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);
});

How to use Adobe Illustrator Scripting for Artboard?

I'm trying to load my SVG-images as layers folder onto a current document. Somehow I'm able to manage it for new document by using the script below but what I need is that I want to import all my images to current opened document. Can someone suggest how I can change the script below for doing this task?
Script source code is:
function getFolder() {
return Folder.selectDialog('Please select the folder to be imported:', Folder('~'));
}
function importFolderAsLayers(selectedFolder) {
// if a folder was selected continue with action, otherwise quit
var document;
var mm = 2.83464567; // Metric MM converter…
// Set the script to work with artboard rulers
app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM;
if (selectedFolder) {
document = app.documents.add(
DocumentColorSpace.RGB,
width = 720*mm,
height = 720*mm,
);
document = app.activeDocument;
var firstImageLayer = true;
var newLayer;
var thisPlacedItem;
var posX=10;
var posY=30;
var count=0;
// create document list from files in selected folder
var imageList = selectedFolder.getFiles();
for (var i = 0; i < imageList.length; i++) {
if (imageList[i] instanceof File) {
var fileName = imageList[i].name.toLowerCase();
if( (fileName.indexOf(".svg") == -1) ) {
continue;
} else {
if( firstImageLayer ) {
newLayer = document.layers[0];
firstImageLayer = false;
} else {
newLayer = document.layers.add();
}
// Give the layer the name of the image file
newLayer.name = fileName.substring(0, fileName.indexOf(".") );
// Place the image on the artboard
newGroup = newLayer.groupItems.createFromFile( imageList[i] );
newGroup.position = [ posX , posY ];
}
}
posX += newGroup.width;
if(posX > (newGroup.width*16)) {
posX = 0;
posY -= newGroup.height;
}
}
if( firstImageLayer ) {
// alert("The action has been cancelled.");
// display error message if no supported documents were found in the designated folder
alert("Sorry, but the designated folder does not contain any recognized image formats.\n\nPlease choose another folder.");
document.close();
importFolderAsLayers(getFolder());
}
} else {
// alert("The action has been cancelled.");
// display error message if no supported documents were found in the designated folder
alert("Rerun the script and choose a folder with images.");
//importFolderAsLayers(getFolder());
}
}
// Start the script off
importFolderAsLayers( getFolder() );
Simply remove these lines from your script:
document = app.documents.add(
DocumentColorSpace.RGB,
width = 720*mm,
height = 720*mm,
);

jQuery File Upload - get size of uploaded images

I am using the jQuery File Upload to upload product images. There are different "types" of images for each product (different size/dimensions).
I have altered the upload template so that a dropdown of possible image types is shown for each file added. Before clicking upload, the user must pick from the dropdown to indicate what image type the file being uploaded is.
Some image types are an exact size, some just have a minimum width. What I want to do is compare the actual image size to the type chosen to validate they are indicating the correct type.
I'm attempting to do this via the "fileuploadsubmit" callback where I have already added a check to make sure an option is selected in the dropdown.
$('#fileupload').bind('fileuploadsubmit', function (e, data) {
$('#uploading_note').removeClass("alert-danger").html("");
var inputs = data.context.find(':input');
if (inputs.filter(function () {
return !this.value && $(this).prop('required');
}).first().focus().length) {
data.context.addClass("alert-danger");
data.context.find('.file_msg').html("Image Type is required!");
data.context.find('button').prop('disabled', false);
return false;
}
var fixed_dimension = 0;
var wt = 0;
var ht = 0;
var image_size = getImageSize(data,function(width, height) {
wt = width;
ht = height;
console.log (wt+'x'+ht);
return [wt,ht];
});
...........
This is the getImageSize function.
function getImageSize(data,callback){
var img = new Image();
img.src = _URL.createObjectURL(data.files[0]);
img.onload = function () {
var w = this.width;
var h = this.height;
console.log(w+'-getImageSize-'+h);
callback (w,h);
};
}
The console.log() in both output correctly but I can't get these numbers outside the functions to use them. I understand it has to do with the functions be asynchronous but I can't figure out how to get around it. Or maybe there is a better jQuery File Upload built in option I'm missing.
I understand the asynchronous function issue, this one was attempt at finding a solution to validating the image size. I have also attempted to do this in the PHP script. It works in that I can prevent the upload of an image but the user experience is poor. So I am still looking for a solution as to how to do image size validation using jQuery File Upload.
Below is an update version of the code.
$('#fileupload').bind('fileuploadsubmit', function (e, data) {
console.log(data);
$('#uploading_note').removeClass("alert-danger").html("");
var inputs = data.context.find(':input');
if (inputs.filter(function () {
return !this.value && $(this).prop('required');
}).first().focus().length) {
console.log(data.context);
data.context.addClass("alert-danger");
data.context.find('.file_msg').html("Image Type is required!");
//$('#uploading_note').addClass("alert-danger").html("Image Type is required!");
data.context.find('button').prop('disabled', false);
return false;
}
var fixed_dimension = 0;
var wt = 0;
var ht = 0;
var image_size = getImageSize(data,function(width, height) {
wt = width;
ht = height;
console.log(wt+'-getImageSize-function'+ht);
switch (inputs[0].value){
case "16x9_background":
case "16x9":
var req_width = 1920;
var req_height = 1080;
fixed_dimension = 1;
break;
case "3x4":
var req_width = 1600;
var req_height = 1200;
fixed_dimension = 1;
break;
case "hires":
var req_width = 1400;
var req_height = 0;
break;
case "lowres":
var req_width = 200;
var req_height = 0;
break;
}
if (fixed_dimension){
if (wt != req_width || ht != req_height){
data.context.addClass("alert-danger");
data.context.find('.file_msg').html("Image dimensions must be exactly "+req_width+"x"+req_height+". This image is "+wt+"x"+ht+". Image not uploaded.");
return false;
}
} else {
if (wt < req_width){
data.context.addClass("alert-danger");
data.context.find('.file_msg').html("Image dimensions wrong!! Width must be "+req_width+", not "+wt+". Image not uploaded.");
console.log(wt+'x'+ht);
return false;
}
}
d = inputs.serializeArray();
d.push({ name: "folder", value: $('#barcode').val() });
d.push({ name: "stock_num", value: $('#stock_num').val() });
data.formData = d;
console.log(wt+"xxxx"+ht);
data.submit(); // SUMBIT THE FORM
});
console.log(wt+"xxxx"+ht);
console.log("imagesize:"+image_size);
return false; //STOP THE DEFAULT SUBMIT
});
What I ended up doing was removing the actual form submit button and replace it with a button (not type submit) that calls the validation code. If it passes, the form is then submitted normally (via data.submit()), if not it returns the error. I had to remove the file level submit buttons (or I found it easier to do that).
$('#fileupload').fileupload({
url: 'process.php',
previewThumbnail: true,
sequentialUploads: true,
acceptFileTypes: /(\.|\/)(jpe?g|pdf|zip)$/i,
maxChunkSize: 10000000,
add: function (e, data) {
$('#start_upload_button').click(function () {
getImageSize3(data).then(function(dimensions) {
image validation... return false if any errors
data.submit() // submit the form
});

Javascript EXIF Image Orientation and Image Preview

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

Categories

Resources