Strip EXIF data from image - javascript

How can I strip the EXIF data from an uploaded image through javascript? I am currently able to access the EXIF data using this exif-js plugin, like this:
EXIF.getData(oimg, function() {
var orientation = EXIF.getTag(this, "Orientation");
});
However, I have not found any way to actually remove the Exif data, only to retrieve it.
More specifically, I am trying to do this to get rid of the orientation Exif data which rotates my image on certain browsers.

look up the file format and exif format
read the file into arraybuffer
find the required data and remove it
create a blob from the remaining data
upload it with ajax
Here is a little demo of it, select an image with orientation data to see how it looks with and with out it(modern browsers only).
http://jsfiddle.net/mowglisanu/frhwm2xe/3/
var input = document.querySelector('#erd');
input.addEventListener('change', load);
function load(){
var fr = new FileReader();
fr.onload = process;
fr.readAsArrayBuffer(this.files[0]);
document.querySelector('#orig').src = URL.createObjectURL(this.files[0]);
}
function process(){
var dv = new DataView(this.result);
var offset = 0, recess = 0;
var pieces = [];
var i = 0;
if (dv.getUint16(offset) == 0xffd8){
offset += 2;
var app1 = dv.getUint16(offset);
offset += 2;
while (offset < dv.byteLength){
//console.log(offset, '0x'+app1.toString(16), recess);
if (app1 == 0xffe1){
pieces[i] = {recess:recess,offset:offset-2};
recess = offset + dv.getUint16(offset);
i++;
}
else if (app1 == 0xffda){
break;
}
offset += dv.getUint16(offset);
var app1 = dv.getUint16(offset);
offset += 2;
}
if (pieces.length > 0){
var newPieces = [];
pieces.forEach(function(v){
newPieces.push(this.result.slice(v.recess, v.offset));
}, this);
newPieces.push(this.result.slice(recess));
var br = new Blob(newPieces, {type: 'image/jpeg'});
document.querySelector('#mod').src = URL.createObjectURL(br);
}
}
}
img{
max-width:200px;
}
<input id="erd" type="file"/><br>
<img id="orig" title="Original">
<img id="mod" title="Modified">

Related

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

Sending image manipulated via JS in AJAX POST request

I'm a server-side dev learning the ropes of vanilla JS. I need to clear my concepts regarding sending an Ajax POST request for an image object I'm creating in JS - this question is about that.
Imagine a web app where users upload photos for others to see. At the point of each image's upload, I use vanilla JS to confirm the image's mime-type (via interpreting magic numbers), and then resize the image for optimization purposes.
After resizing, I do:
var canvas = document.createElement('canvas');
canvas.width = resized_width;
canvas.height = resized_height;
var ctx = canvas.getContext("2d");
ctx.drawImage(source_img, 0, 0, resized_width, resized_height);
var resized_img = new Image();
resized_img.src = canvas.toDataURL("image/jpeg",0.7);
return resized_img;
The image object returned has to be sent to the backend via an Ajax request. Something like:
function overwrite_default_submit(e) {
e.preventDefault();
var form = new FormData();
form.append("myfile", resized_img, img_name);
var xhr = new XMLHttpRequest();
xhr.open('POST', e.target.action);
// xhr.send(form); // uncomment to really send the request
}
However, the image object returned after resizing is essentially an HTML element like so <img src="data:image/jpeg;base64>. Whereas the object expected in the FormData object ought to be a File object, e.g. something like: File { name: "example.jpg", lastModified: 1500117303000, lastModifiedDate: Date 2017-07-15T11:15:03.000Z, webkitRelativePath: "", size: 115711, type: "image/jpeg" }.
So what do I do to fix this issue? Would prefer to learn the most efficient way of doing things here.
Btw, I've seen an example on SO of using the JS FILE object, but I'd prefer a more cross-browser method, given File garnered support from Safari, Opera Mobile and built-in Android browsers relatively recently.
Moreover, only want pure JS solutions since I'm using this as an exercise to learn the ropes. JQuery is on my radar, but for later.
The rest of my code is as follows (only included JPEG processing for brevity):
var max_img_width = 400;
var wranges = [max_img_width, Math.round(0.8*max_img_width), Math.round(0.6*max_img_width),Math.round(0.4*max_img_width),Math.round(0.2*max_img_width)];
// grab the file from the input and process it
function process_user_file(e) {
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = process_image;
reader.readAsArrayBuffer(file.slice(0,25));
}
// checking file type programmatically (via magic numbers), getting dimensions and returning a compressed image
function process_image(e) {
var img_width;
var img_height;
var view = new Uint8Array(e.target.result);
var arr = view.subarray(0, 4);
var header = "";
for(var i = 0; i < arr.length; i++) {
header += arr[i].toString(16);
}
switch (header) {
case "ffd8ffe0":
case "ffd8ffe1":
case "ffd8ffe2":
case "ffd8ffe3":
case "ffd8ffe8":
// magic numbers represent type = "image/jpeg";
// use the 'slow' method to get the dimensions of the media
img_file = browse_image_btn.files[0];
var fr = new FileReader();
fr.onload = function(){
var dataURL = fr.result;
var img = new Image();
img.onload = function() {
img_width = this.width;
img_height = this.height;
resized_img = resize_and_compress(this, img_width, img_height, 80);
}
img.src = dataURL;
};
fr.readAsDataURL(img_file);
to_send = browse_image_btn.files[0];
load_rest = true;
subform.disabled = false;
break;
default:
// type = "unknown"; // Or one can use the blob.type as fallback
load_rest = false;
subform.disabled = true;
browse_image_btn.value = "";
to_send = null;
break;
}
}
// resizing (& compressing) image
function resize_and_compress(source_img, img_width, img_height, quality){
var new_width;
switch (true) {
case img_width < wranges[4]:
new_width = wranges[4];
break;
case img_width < wranges[3]:
new_width = wranges[4];
break;
case img_width < wranges[2]:
new_width = wranges[3];
break;
case img_width < wranges[1]:
new_width = wranges[2];
break;
case img_width < wranges[0]:
new_width = wranges[1];
break;
default:
new_width = wranges[0];
break;
}
var wpercent = (new_width/img_width);
var new_height = Math.round(img_height*wpercent);
var canvas = document.createElement('canvas');
canvas.width = new_width;
canvas.height = new_height;
var ctx = canvas.getContext("2d");
ctx.drawImage(source_img, 0, 0, new_width, new_height);
console.log(ctx);
var resized_img = new Image();
resized_img.src = canvas.toDataURL("image/jpeg",quality/100);
return resized_img;
}
Update: I'm employing the following:
// converting image data uri to a blob object
function dataURItoBlob(dataURI,mime_type) {
var byteString = atob(dataURI.split(',')[1]);
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) { ia[i] = byteString.charCodeAt(i); }
return new Blob([ab], { type: mime_type });
}
Where the dataURI parameter is canvas.toDataURL(mime_type,quality/100)
You should call the canvas.toBlob() to get the binary instead of using a base64 string.
it's async so you would have to add a callback to it.
canvas.toBlob(function(blob) {
resized_img.onload = function() {
// no longer need to read the blob so it's revoked
URL.revokeObjectURL(this.url);
};
// Preview the image using createObjectURL
resized_img.src = URL.createObjectURL(blob);
// Attach the blob to the FormData
var form = new FormData();
form.append("myfile", blob, img_name);
}, "image/jpeg", 0.7);
See to this SO post: How to get base64 encoded data from html image
I think you need to call 'canvas.toDataURL()' to get the actual base64 stream of the image.
var image = canvas.toDataURL();
Then upload it with a Form: Upload a base64 encoded image using FormData?
var data = new FormData();
data.append("image_data", image);
Untested, but this should be about it.

Rotate image on lightbox2 load

I would like to detect EXIF rotation information when lightbox shows an image and apply CSS for rotation.
I use thumbnails with img src attribute value of base64 encoded image data (I use no href attribute for link to original image)
I do not have the option to use server-side code.
It would be best if it happened just before render. Are there any events in lightbox2 like onPreShow or onLoad ?
I had to modify the preloader.onload handler inside the Lightbox.prototype.changeImage function.
I added the orientation detection code before this code:
$image.width(preloader.width);
$image.height(preloader.height);
imgHeight and imgWidth are swapped and css is added in my code if image orientation is landscape.
$preloader = $(preloader);
var imgHeight = preloader.height;
var imgWidth = preloader.width;
EXIF.getData(preloader, function() {
var rotation = EXIF.getTag(this, "Orientation");
if (rotation == 6 || rotation == 8) {
var css = exif2css(rotation);
if (css.transform) {
$image[0].style.transform = css.transform;
}
if (css['transform-origin']) {
$image[0].style['transform-origin'] = css['transform-origin'];
}
console.log("rotate");
var tmp = imgHeight;
imgHeight = imgWidth;
imgWidth = tmp;
} else {
//clear css
$image[0].style.transform = "";
$image[0].style['transform-origin'] = "";
}
$image.width(imgWidth);
$image.height(imgHeight);
if (self.options.fitImagesInViewport) {
...
});

How to add a 16x16 grid of pseudo-random tiles as a background in canvas (or other web language)

I have recently been working on a web based project using canvas on HTML5. The program consists of a 16x16 grid of tiles that have been pseudo-randomly generated. I am relatively new to canvas, but have built this program in several other environments, none of which however compile successfully to a web based language. this is the main code section that is giving me bother:
var A = 8765432352450986;
var B = 8765432352450986;
var M = 2576436549074795;
var X = 1;
var rx = 0;
var ry = 0;
this.image = new Image();
var i = 0;
var ii = 0;
while(i < 16)
{
while(ii < 16)
{
this.image = new Image();
this.image.src = "textures/grass.png";
x = (((A*X)+B)%M)%M;
if((x/2)%1 == 0)
{
this.image.src = "textures/grass.png";
}
if((x/8)%1 == 0)
{
this.image.src = "textures/hill.png";
}
if((x/21)%1 == 0)
{
this.image.src = "textures/trees.png";
}
if((x/24)%1 == 0)
{
this.image.src = "textures/sea.png";
}
if((x/55)%1 == 0)
{
this.image.src = "textures/mountain.png";
}
if((x/78)%1 == 0)
{
this.image.src = "textures/lake.png";
}
if((x/521)%1 == 0)
{
this.image.src = "textures/volcano.png";
}
if((x/1700)%1 == 0)
{
this.image.src = "textures/shrine.png";
}
if((x/1890)%1 == 0)
{
this.image.src = "textures/outpost.png";
}
if((x/1999)%1 == 0)
{
this.image.src = "textures/civ.png";
}
ctx = myGameArea.context;
ctx.drawImage(this.image,rx, ry, 20, 20);
ii ++;
rx += 20;
}
i ++;
rx = 0;
ry += 16;
}
I would like canvas to draw along the lines of this code above, effectively generating a grid like this
pre generated grid image
(please try and ignore the obvious bad tile drawings, I planned on either finding an artist or trying slightly harder on them when I get the game fully working.)
The black square is a separate movable object. I haven't got as far as implementing it in this version, but if you have any suggestions for it please tell me
in the full html file I have now, the canvas renders but none of the background (using the w3schools tutorials, I can make objects render however)
In short: how do I render a background consisting of a 16x16 grid of pseudo-random tiles on an event triggered or on page loaded, using canvas or if that does not work another web based technology
Thank you for your time.
A few problems but the main one is that you need to give an image some time to load before you can draw it to the canvas.
var image = new Image();
image.src = "image.png";
// at this line the image may or may not have loaded.
// If not loaded you can not draw it
To ensure an image has loaded you can add a onload event handler to the image
var image = new Image();
image.src = "image.png";
image.onload = function(){ ctx.drawImage(image,0,0); }
The onload function will be called after all the current code has run.
To load many images you want to know when all have loaded. One way to do this is to count the number of images you are loading, and then use the onload to count the number of images that have loaded. When the loaded count is the same as the loading count you know all have loaded and can then call a function to draw what you want with the images.
// Array of image names
const imageNames = "grass,hill,trees,sea,mountain,lake,volcano,shrine,outpost,civ".split(",");
const images = []; // array of images
const namedImages = {}; // object with named images
// counts of loaded and waiting toload images
var loadedCount = 0;
var imageCount = 0;
// tile sizes
const tileWidth = 20;
const tileHeight = 20;
// NOT SURE WHERE YOU GOT THIS FROM so have left it as you had in your code
// Would normally be from a canvas element via canvasElement.getContext("2d")
var ctx = myGameArea.context;
// seeded random function encapsulated in a singleton
// You can set the seed by passing it as an argument rand(seed) or
// just get the next random by not passing the argument. rand()
const rand = (function(){
const A = 8765432352450986;
const B = 8765432352450986; // This value should not be the same as A?? left as is so you get the same values
const M = 2576436549074795;
var seed = 1;
return (x = seed) => seed = ((A * x) + B) % M;
}());
// function loads an image with name
function addImage(name){
const image = new Image;
image.src = "textures/" + name + ".png";
image.onload = () => {
loadedCount += 1;
if(loadedCount === imageCount){
if(typeof allImagesLoaded === "function"){
allImagesLoaded();
}
}
}
imageCount += 1;
images.push(image);
namedImages[name] = image;
}
imageNames.forEach(addImage); // start loading all the images
// This function draws the tiles
function allImagesLoaded(){ /// function that is called when all the images have been loaded
var i, x, y, image;
for(i = 0; i < 256; i += 1){ // loop 16 by 16 times
ctx.drawImage(
images[Math.floor(rand()) % images.length]; //random function does not guarantee an integer so must floor
(i % 16) * tileWidth, // x position
Math.floor(i / 16) * tileHeight, // y position
tileWidth, tileHeight // width and height
);
}
}

<img>width returns 0 under heavy load

The below handleFiles method is being passed files from both drag and drop and a file input. After it gets the data url for a given file it passes it to the processImage function. This function creates a new image and sets the src and file for that image. I then take different actions based on the width of the incoming image and insert the image into the dom. However, I noticed when dropping in a bunch of images imageWidth will get set to 0. I have confirmed the image.src is correctly set and that dropping the same image in by itself works fine. I also have confirmed that if I remove the width calculations the image does display correctly on the page. When I enter the debugger I can confirm that immediately after imageWidth is set to 0 i.width returns a correct value. At first I thought it might be a threading issue in Chrome, but then when I saw it happen in FireFox as well I became alarmed. I have not been able to pinpoint a certain threshold, but the more load you put on the browser the less likely it is to correctly get the width.
I am seeing the problem in both FireFox 16.0.2 and Chrome 23.0.1271.95.
function handleFiles(files) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
if( !isImage(file) ) {
continue;
}
var reader = new FileReader();
reader.onloadend = function(e) {
var dataURL = e.target.result;
processImage(file, dataURL);
}
reader.readAsDataURL(file);
}
}
function processImage(file, dataURL) {
var i = new Image();
i.src = dataURL;
i.file = file;
//console.log(i);
var maxWidth = 600;
var imageWidth = i.width;
......
}
As with all images, they may need time to load before they will tell you their width:
var i = new Image();
i.onload = function() {
//console.log(i);
var maxWidth = 600;
var imageWidth = this.width;
}
i.src = dataURL;
i.file = file;
The width (and height) might be 0 because it's not loaded yet.
Try adding the load event like so:
function processImage(file, dataURL) {
var i = new Image();
i.addEventListener("load", function () {
var maxWidth = 600;
var imageWidth = i.width;
......
});
i.src = dataURL;
i.file = file;
}

Categories

Resources