I am trying to extract a jpg image from a pdf file. Please take a look at a reproducible example:
https://codepen.io/thomas-kertsalis/pen/YzpYwYo?editors=1111
window.objs=[];
pdfjsLib.getDocument(sURL).promise
.then(pdf => {
for(var i=1;i<(pdf.numPages+1);i++){
pdf.getPage(i).then(function(page) {
page.getOperatorList().then(function (ops) {
for (var i=0; i < ops.fnArray.length; i++) {
let currentElement=ops.argsArray[i];
if(ops.fnArray[i] == pdfjsLib.OPS.paintImageXObject) {
window.objs.push(ops.argsArray[i][0])
let imageName=ops.argsArray[i][0];
page.objs.get(imageName, function(img) {
const content = img.data;
var newB64 = btoa(content);
document.getElementById("my-img").src =
'data:image/png;base64,'+newB64;
}
}
}
}
}
}
}
Related
I have an array of pictures that are from mulitple sub-folders. I am trying to do the if loop to see if the files from the array are located in the following folders without writting each file and it's full local path.
let i = 0;
let imageArray = [];
let time = 2000;
imageArray = [
"winhistory.jpg",
"winsymbol.png",
"10.jpg",
"win08diskprop.jpg",
"win98install.jpg",
"Windows-logo.jpg"
];
const imageDir = imageArray => {
if ((document.slide.src = "../images/windowspics/")) {
"../images/windowspics/" + imageArray[i];
} else if ((document.slide.src = "../images/coins/")) {
"../images/coins/" + imageArray[i];
} else if ((document.slide.src = "../images/codelang/")) {
"../images/codelang/" + imageArray[i];
}
return imageArray;
};
const changeImg = () => {
if (i < imageArray.length - 1) {
i++;
} else {
i = 0;
}
setTimeout("changeImg()", time);
window.onload = changeImg;
};
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
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.
I want to upload list of images from a folder and stored them as bytestream in database. I want to give angularjs the folder containing the images instead of selecting multiple files . The part of the code responsible is given below.
$scope.uploadMultipleQuestions = function(e) {
var questionList = []
var difficultyLevel = vm.question.difficultyLevel;
var theFiles = e.files;
for (var i = 0; i < theFiles.length; i++) {
var ques = {};
ques.questionString = theFiles[i].name;
DataUtils.toBase64(theFiles[i], function(base64Data) {
$scope.$apply(function() {
ques.questionImage = base64Data;
});
[![enter image description here][1]][1]
});
ques.questionImageContentType = theFiles[i].type;
ques.questionString = theFiles[i].webkitRelativePath.split("/")[1];
questionList.push(ques);
Question.uploadMultipleQuestions(questionList);
}
for (var i = 0; i < questionList.length; i++) {
console.log(questionList[i]);
}
//Question.uploadMultipleQuestions(questionList);
}
But the problem is I am getting the following details in my log.(Screenshot attached below)
As you can see only the last object contains image data whereas none of the others have any image content.
Let me know why this problem is coming and how to solve the same.
It take a while to convert image to base64, so you have to upload your image after ques.questionImage is filled.
var uploadMultipleQuestions = function(files, i, output) {
if (files.length == i) {
for(var j=0;j<output.length;j++)
console.log(output[j]);
return Question.uploadMultipleQuestions(output);
}
DataUtils.toBase64(files[i], function(base64Data) {
output.push({
questionString: files[i].name,
questionImageContentType: files[i].type,
questionString: files[i].webkitRelativePath.split("/")[1],
questionImage: base64Data
});
uploadMultipleQuestions(files, i+1, output);
});
}
$scope.uploadMultipleQuestions =function(e){
var theFiles = e.files;
uploadMultipleQuestions(theFiles, 0, []);
}
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 :/