Javascript Image Converter (base64) with all formats - javascript

I'm trying to script a converter (image) that pickup the checksum inside a image (form my Server) and add it to the selected image file.
But there I got 2 problems:
First problem:
It just accept jpg files, I tried everythink, but it dont work (png, gif etc.)
The second problem is, that the valid image, need to be from my server (convert.jpg)
But if I do that, I get this error:
TypeError: Argument 1 of FileReader.readAsDataURL is not an
object.
The line:
readerValid.readAsDataURL(valid);
What did I do wrong? (And sry for my bad english)
My Code:
function hexToBytes(hex) {
for (var bytes = [], c = 0; c < hex.length; c += 2)
bytes.push(parseInt(hex.substr(c, 2), 16));
return bytes;
}
function bytesToHex(bytes) {
for (var hex = [], i = 0; i < bytes.length; i++) {
hex.push((bytes.charCodeAt(i) >>> 4).toString(16));
hex.push((bytes.charCodeAt(i) & 0xF).toString(16));
}
return hex.join("");
}
function UpdateChecksum(pic, data) {
var string = ""
for (var i = 0; i < data.length; ++i) {
string += String.fromCharCode(data[i])
}
pic = atob(pic.replace(/^data:image\/jpeg;base64,/, ""))
for (var i = 0; i + 1 < pic.length; ++i) {
if (pic.charCodeAt(i) == 0xFF && pic.charCodeAt(i + 1) == 0xDB) {
pic = pic.slice(i, pic.length)
break
}
}
var regexp = new RegExp("(<checksum2>[0-9a-f]{32}</checksum2>)")
var match = regexp.exec(string)
string = string.replace(match[1], "<checksum2>" + bytesToHex(rc4("bns_gamepic", hexToBytes(md5(pic)))) + "</checksum2>")
for (var i = 0; i < data.length; ++i) {
data[i] = string.charCodeAt(i)
}
return data
}
function process() {
if(document.getElementById("custom").value == ""){
document.getElementById('error').innerHTML="Chose Image!";
}
else{
var valid = "convert.jpg";
var custom = document.getElementById('custom').files[0]
var readerValid = new FileReader()
readerValid.onloadend = function(e) {
var exif = piexif.load(e.target.result)
var readerCustom = new FileReader()
readerCustom.onloadend = function(e) {
var image = new Image()
image.onload = function() {
var result
try {
result = piexif.remove(e.target.result)
} catch (err) {
result = e.target.result
}
exif["Exif"][700] = UpdateChecksum(result, exif["Exif"][700])
result = piexif.insert(piexif.dump(exif), result)
download(result, "Converted_Image.jpg", "image/jpeg");
}
image.src = e.target.result
}
readerCustom.readAsDataURL(custom);
};
readerValid.readAsDataURL(valid);
}
}
I hope you can help me
Someone said:
The code var valid = "convert.jpg"; defines valid as a string, but the function readAsDataURL expect an object of type blob as a parameter, not a string.
But:
var valid = new Blob(["convert.jpg"], { type: 'image/jpeg'});
dont work :/

Related

Comparing JPG files with Photoshop Layers

Is it possible to compare filenames for a set of files that are imported as Photoshop layers ?
I have a folder of 50 jpg images which I have used in a PSD file.
Now I want to check whether all the JPG files are used or not ?
Is it possible to do so ?
As I've said, Photoshop scripting can help you achieve this by using File Objects and basic javascript knowledge. I've modified my old script as you've desired and now it should work well with any nested groups and images.
I highly encourage you to learn scripting and ask questions here wherever you feels confused.
Save below code as 'Script.jsx' and run it from 'File > Scripts > Browse'
Update 2 : Now it saves log.txt file too as per you requested. P.S. Learn from this script and tweak it to your desired result.
// Managing Document
var docs = app.documents;
// Progress Bar
var win = new Window("window{text:'Progress',bounds:[100,100,400,150],bar:Progressbar{bounds:[20,20,280,31] , value:0,maxvalue:100}};");
// assigning activeDocument
if (docs.length != 0) {
var docRef = app.activeDocument;
// Defining the folder
alert("You will be prompted for the folder containing your images.\n" +
"Files will be selected with a '.png'/'.jpg/.jpeg' on the end in the same folder.");
var folder = Folder.selectDialog();
if (!folder) {
exit;
}
var photoFiles = folder.getFiles(/\.(jpg|jpeg|png)$/i);
var matchFiles = [];
var photoFilesName = [];
//Searching for used images
var increment = parseFloat(0);
var divider = parseFloat(100/photoFiles.length);
win.show();
for (var i = 0; i < photoFiles.length; i++) {
increment = increment + divider;
var indexPhotoName = removeExtension(photoFiles[i].displayName);
photoFilesName.push(indexPhotoName);
var doc = activeDocument;
var curLayer;
goThroughLayers(doc, indexPhotoName);
}
function goThroughLayers(parentLayer, targetName) {
for (var i = 0; i < parentLayer.layers.length; i++) {
curLayer = parentLayer.layers[i];
doc.activeLayer = curLayer;
if (curLayer.typename == 'LayerSet') {
goThroughLayers(curLayer, targetName)
} else {
if (curLayer.name == targetName) {
// if (curLayer.name.match(/[e]/ig)) {
matchFiles.push(targetName);
// }
} //end if
} //end else
} //end loop
} //end function
function arr_diff(a1, a2) {
var a = [],
diff = [];
for (var i = 0; i < a1.length; i++) {
a[a1[i]] = true;
}
for (var i = 0; i < a2.length; i++) {
if (a[a2[i]]) {
delete a[a2[i]];
} else {
a[a2[i]] = true;
}
}
for (var k in a) {
diff.push(k);
}
return diff;
}
function removeExtension(str) {
return str.split('.').slice(0, -1).join('.');
}
var missItems = arr_diff(matchFiles, photoFilesName);
if (missItems.length > 0) {
var missFolder = new Folder(photoFiles[0].path + '/Missed%20Files');
if(!missFolder.exists){
missFolder.create();
}
for (var y = 0; y < photoFiles.length; y++) {
var photoTrimName = removeExtension(photoFiles[y].displayName);
for( var x = 0; x < missItems.length ; x++){
if(photoTrimName == missItems[x]){
photoFiles[y].copy(new File(missFolder+'/'+photoFiles[y].displayName));
}
}
};
win.close();
alert("You've missed total " + missItems.length + " files. Press OK to open folder containing missing files. Log report is generated wherever PSD is saved.");
var FileStr = "";
for(var m=0; m<missItems.length; m++){
FileStr = FileStr + '\n' + (m+1) + '. ' + missItems[m];
}
var str = "Your missed files are : " + FileStr;
saveTxt(str);
missFolder.execute();
} else {
win.close();
saveTxt('All Photos are used');
alert('All Photos are used');
}
} else {
alert('Open atleast one document');
}
function saveTxt(txt)
{
var Name = "LogReport_" + app.activeDocument.name.replace(/\.[^\.]+$/, '');
var Ext = decodeURI(app.activeDocument.name).replace(/^.*\./,'');
if (Ext.toLowerCase() != 'psd')
return;
var Path = app.activeDocument.path;
var saveFile = File(Path + "/" + Name +".txt");
if(saveFile.exists)
saveFile.remove();
saveFile.encoding = "UTF8";
saveFile.open("e", "TEXT", "????");
saveFile.writeln(txt);
saveFile.close();
}
In Javascript, it is possible to get some information related to PSD file layers using PSD.js library

How to filter Cyrillic words in gmail using Google App Script

please help!
My goal is to filter the gmail inbox messages with Google App Script and find the specified Cyrillic word in it.
For example, I have a function that parse the messages:
var parseRawContent = function(rawContent)
{
var lines = rawContent.split("\n");
var result = {};
var headers = {};
var body = "";
var currentHeaderKey = null;
var headerParsed = false;
for (var i = 0; i < lines.length; i++) {
if (lines[i].trim() === "") {
if (headers.date === undefined) {
continue;
}
headerParsed = true;
continue;
}
if (!headerParsed) {
var headerParts = lines[i].match(/^([-a-z]+):(.*)/i);
if (headerParts) {
currentHeaderKey = headerParts[1].toLowerCase();
headers[currentHeaderKey] = headerParts[2].trim();
} else {
// Header continues on new line
headers[currentHeaderKey] += " " + lines[i].trim();
}
} else {
body += lines[i];
}
}
if (headers["content-transfer-encoding"] === "base64") {
try {
body = Utilities.newBlob(Utilities.base64Decode(body)).getDataAsString();
} catch (err) {
getLogger().log("Could not base64 decode body.")
}
}
result.headers = headers;
result.body = body;
return result;
};
Also, I have a function to spot the Russian text in the raw messages:
function(m, raw) {
"Has 'привет' in body"
return raw.body.match(/привет/i)
},
All the code above is taken from (https://github.com/spamzero/spamzero/blob/master/spam-zero.js)
Problem: the match does not happen.
What might be an issue?
Thank you
UPD: I found following issues with parsing the Gmail messages/threads
Russian text can be encoded with "Quoted Printable" encoding;
Russian text can be encoded with "Base64" encoding;
To manage all above the following changes were made for the original functions.
Parse function:
var parseRawContent = function(rawContent) {
var lines = rawContent.split("\n");
var result = {};
var headers = {};
var body = "";
var currentHeaderKey = null;
for (var i = 0; i < lines.length; i++) {
// Checking that the line is a header (starts with "<something>:")
var headerParts = lines[i].match(/^([-a-z]+):(.*)/i);
if (headerParts) {
currentHeaderKey = headerParts[1].toLowerCase();
headers[currentHeaderKey] = headerParts[2].trim();
} else {
// Decode Quoted-Printable to UTF-8 if applicable
if (headers["content-transfer-encoding"] === "quoted-printable") {
// check that the line is started with "=A0" or similar:
if (lines[i].match(/^=[0-9A-H]{2}=(.*)/)) {
try {
lines[i] = lines[i].replace(/=\s$/g, ''); // Replace the last "="
lines[i] = lines[i].replace(/={1}/g, '%'); // Replace all the "=" with "%" for decodeURI method
lines[i] = lines[i].split(" "); // Split the line into the words divided by space
var DecodedLine = ""
for (var j = 0; j < lines[i].length; j++) {
var SubLines = "";
SubLines = decodeURI(lines[i][j]);
DecodedLine += SubLines;
}
lines[i] = DecodedLine;
} catch (err) {
getLogger().log("Could not quoted-printable decode body.")
}
} else {
continue
}
}
// Decode base64 to UTF-8 if applicable
if (headers["content-transfer-encoding"] === "base64") {
try {
lines[i] = Utilities.newBlob(Utilities.base64Decode(lines[i])).getDataAsString();
} catch (err) {
getLogger().log("Could not base64 decode body.")
}
}
// Add everything that is not a header incl. decoded lines to BODY
body += lines[i];
}
}
result.headers = headers;
result.body = body;
return result;
};
Spot function:
function(m, raw) {
"Has Russian words 'тест' or 'привет' in body"
var matchers = [/тест/i, /привет/i
]
for (var i = 0; i < matchers.length; i++) {
if (raw.body.match(matchers[i])) {
return true;
}
}
},
An issue has been closed.
P.S.: I am a noob in coding. Please do not hesitate to comment/suggest more efficient solution.

What is the correct way to send large CSV Files to Server using jquery

I have a CSV file with ~20,000 records. I send each line using the $.post method to my server using the FileReader API.
The problem is that the browser is buffering each record before starting to send the data and this way is very slow. I want to send each line separately to show a progressbar where it counts the request number of each line.
As this solution is very slow I'm thinking there are must be other ways of doing this to make it faster. Many thanks to your ideas.
$("#form_file").change(function(e) {
if (e.target.files != undefined) {
var reader = new FileReader();
reader.onload = function(e) {
var rows = e.target.result.split("\n");
var index = rows[0];
index = index.split(";");
gesamt = rows.length - 1;
for (var i = 1; i < rows.length; i++) {
var row = rows[i];
cells = row.split(";");
var dataset = {};
for (var ii = 0; ii < cells.length; ii++) {
var value = cells[ii];
var key = index[ii]
var printError = function(error, explicit) {
console.log(`[${explicit ? 'EXPLICIT' : 'INEXPLICIT'}] ${error.name}: ${error.message}`);
}
try {
dataset[key] = value;
} catch (e) {
if (e instanceof RangeError) {
if (e.message.toLowerCase().indexOf('invalid array') !== -1) {
printError(e, true);
} else {
printError(e, false);
}
} else {
printError(e, false);
}
}
}
console.log(dataset);
row = insertrow(dataset, i);
$('#progressbar').show();
$('#progressvalue').text(i + '/' + gesamt);
$('#progresstitle').text('(' + dataset.title + ')');
}
};
var test = reader.readAsText(e.target.files.item(0));
}
});
function insertrow(mydata, step) {
var token = "{{app.request.query.get('_token')}}";
mydata = JSON.stringify(mydata);
$.post('preferences/upload?_token=' + token, {
data: mydata
}, function(data) {
$('#info').show();
var html = data.message + '<br />';
$('#info').append(html);
}, "json");
}

chrome only filereader bug

I am trying to read-in a file and calculate the SHA-256 hash.
The code works on localhost perfectly fine (Chrome and Safari).
As soon as I upload the page on a webserver I will get the following error in Google Chrome:
Uncaught TypeError: Cannot read property 'digest' of undefined
at FileReader.reader.onload (hashDocument.js:40)
However, the webpage works fine in Safari as well as on Android devices.
function convertStringToArrayBufferView(str)
{
var bytes = new Uint8Array(str.length);
for (var iii = 0; iii < str.length; iii++)
{
bytes[iii] = str.charCodeAt(iii);
}
return bytes;
}
function convertArrayBufferToHexaDecimal(buffer)
{
var data_view = new DataView(buffer);
var iii, len, hex = '', c;
for(iii = 0, len = data_view.byteLength; iii < len; iii += 1)
{
c = data_view.getUint8(iii).toString(16);
if(c.length < 2)
{
c = '0' + c;
}
hex += c;
}
return hex;
}
function hashIt() {
var nBytes = 0,
oFiles = document.getElementById("documentIn").files,
nFiles = oFiles.length;
for (var nFileId = 0; nFileId < nFiles; nFileId++) {
//console.log(oFiles[nFileId]);
var reader = new FileReader();
reader.onload = function(e) {
var text = reader.result;
var promise = crypto.subtle.digest({name: "SHA-256"}, convertStringToArrayBufferView(text));
promise.then(function(result){
var hashValue = convertArrayBufferToHexaDecimal(result);
// update input field
console.log("hashValue");
$("#documentHash").val(hashValue);
});
};
reader.readAsText(oFiles[nFileId]);
nBytes += oFiles[nFileId].size;
}
}

Grab an image from a div and set it to be a variable in JavaScript (chrome extension)

I am trying to desteghide an image to reveal the secret message.
I have got it working, but only by browsing the image which contains the message.
If you take a look at the screenshot:
To make this work I need to save the image (the arsenal badge). Then use the browse to upload the image again to make this work. I want to skip the browse stage and make automatically by grabbing the image straight from the div.
Any ideas?
here is my code (its quite messy sorry)
window.onload = function() {
// add action to the file input
var input = document.getElementById('file');
input.addEventListener('change', importImage);
};
var maxMessageSize = 1000;
$("#desteg").click(function()
{
decode();
});
var importImage = function(e) {
var reader = new FileReader();
reader.onload = function(event) {
// set the preview
document.getElementById('preview').style.display = 'block';
document.getElementById('preview').src = event.target.result;
// wipe all the fields clean
document.getElementById('pass').value = '';
document.getElementById('ContentArea').innerHTML = '';
// read the data into the canvas element
var img = new Image();
img.onload = function() {
var ctx = document.getElementById('canvas').getContext('2d');
ctx.canvas.width = img.width;
ctx.canvas.height = img.height;
ctx.drawImage(img, 0, 0);
decode();
};
img.src = event.target.result;
};
reader.readAsDataURL(e.target.files[0]);
};
// encode the image and save it
// decode the image and display the contents if there is anything
var decode = function() {
var password = document.getElementById('pass').value;
var passwordFail = 'Password is incorrect or there is nothing here.';
// decode the message with the supplied password
var ctx = document.getElementById('canvas').getContext('2d');
var imgData = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height);
var message = decodeMessage(imgData.data, sjcl.hash.sha256.hash(password));
// try to parse the JSON
var obj = null;
try {
obj = JSON.parse(message);
} catch (e) {
// display the "choose" view
if (password.length > 0) {
alert(passwordFail);
}
}
// display the "reveal" view
if (obj) {
// decrypt if necessary
if (obj.ct) {
try {
obj.text = sjcl.decrypt(password, message);
} catch (e) {
alert(passwordFail);
}
}
// escape special characters
var escChars = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
'\'': ''',
'/': '/',
'\n': '<br/>'
};
var escHtml = function(string) {
return String(string).replace(/[&<>"'\/\n]/g, function (c) {
return escChars[c];
});
};
document.getElementById('ContentArea').innerHTML = escHtml(obj.text);
}
};
// returns a 1 or 0 for the bit in 'location'
var getBit = function(number, location) {
return ((number >> location) & 1);
};
// sets the bit in 'location' to 'bit' (either a 1 or 0)
var setBit = function(number, location, bit) {
return (number & ~(1 << location)) | (bit << location);
};
// returns an array of 1s and 0s for a 2-byte number
var getBitsFromNumber = function(number) {
var bits = [];
for (var i = 0; i < 16; i++) {
bits.push(getBit(number, i));
}
return bits;
};
// returns the next 2-byte number
var getNumberFromBits = function(bytes, history, hash) {
var number = 0, pos = 0;
while (pos < 16) {
var loc = getNextLocation(history, hash, bytes.length);
var bit = getBit(bytes[loc], 0);
number = setBit(number, pos, bit);
pos++;
}
return number;
};
// returns an array of 1s and 0s for the string 'message'
var getMessageBits = function(message) {
var messageBits = [];
for (var i = 0; i < message.length; i++) {
var code = message.charCodeAt(i);
messageBits = messageBits.concat(getBitsFromNumber(code));
}
return messageBits;
};
// gets the next location to store a bit
var getNextLocation = function(history, hash, total) {
var pos = history.length;
var loc = Math.abs(hash[pos % hash.length] * (pos + 1)) % total;
while (true) {
if (loc >= total) {
loc = 0;
} else if (history.indexOf(loc) >= 0) {
loc++;
} else if ((loc + 1) % 4 === 0) {
loc++;
} else {
history.push(loc);
return loc;
}
}
};
// encodes the supplied 'message' into the CanvasPixelArray 'colors'
// returns the message encoded in the CanvasPixelArray 'colors'
var decodeMessage = function(colors, hash) {
// this will store the color values we've already read from
var history = [];
// get the message size
var messageSize = getNumberFromBits(colors, history, hash);
// exit early if the message is too big for the image
if ((messageSize + 1) * 16 > colors.length * 0.75) {
return '';
}
// exit early if the message is above an artificial limit
if (messageSize === 0 || messageSize > maxMessageSize) {
return '';
}
// put each character into an array
var message = [];
for (var i = 0; i < messageSize; i++) {
var code = getNumberFromBits(colors, history, hash);
message.push(String.fromCharCode(code));
}
// the characters should parse into valid JSON
return message.join('');
};

Categories