Extendscript Photoshop: Is there a way to save out jpeg with specific KB file sizes for web? - photoshop

I'm trying to utilize the following. what this does is saves out Jpeg accordingly to less then a a certain size set. I was curious if anyone knew a way to specifically direct a filename to get a filesize that is equal to the following or as close as possible.
Filename_160x600.png = Filename_160x600.jpg 39kb
Filename_300x600.png = Filename_300x600.jpg 59kb
Filename_1500x513.png = Filename_1500x513.jpg 150kb
saveJPG(
{
path: activeDocument.path,
maxSize: 50 //size in kbs
})
function saveJPG(_data)
{
if (_data.path == undefined) return false;
_data.name = _data.name == undefined ? activeDocument.name : _data.name;
_data.quality == undefined && _data.quality = 75;
if (!new Folder(_data.path).exists)
{
alert("Output path doesn't exist!"); //you can add a function to create a path if needed
return false
}
var options = new ExportOptionsSaveForWeb(),
jpgFile = new File(_data.path + '/' + getName(_data.name) + '.jpg');
options.format = SaveDocumentType.JPEG;
options.quality = _data.quality;
activeDocument.exportDocument(jpgFile, ExportType.SAVEFORWEB, options);
if (_data.maxSize != undefined)
{
var ms = _data.maxSize * 1000;
if (jpgFile.length > ms)
{
if (!jpgFile.remove())
{
alert('Save file is locked, please make sure it\'s not opened anywhere');
return
};
saveJPG(
{
path: _data.path,
name: _data.name,
maxSize: _data.maxSize,
quality: _data.quality - 2
});
}
};

Related

How to add new fileds/values to line widgets in Barcode mobile view in Odoo14 EE?

Hi i am trying to add two new fields to the Barcode mobile view. I went through the default js code of odoo, but didn't find a way to add my custome fields to it.
Here is the default code
stock_barcode/static/src/js/client_action/lines_widget.js
init: function (parent, page, pageIndex, nbPages) {
this._super.apply(this, arguments);
this.page = page; #don't know where this argument page coming from in argument list.
this.pageIndex = pageIndex;
this.nbPages = nbPages;
this.mode = parent.mode;
this.groups = parent.groups;
this.model = parent.actionParams.model;
this.show_entire_packs = parent.show_entire_packs;
this.displayControlButtons = this.nbPages > 0 && parent._isControlButtonsEnabled();
this.displayOptionalButtons = parent._isOptionalButtonsEnabled();
this.isPickingRelated = parent._isPickingRelated();
this.isImmediatePicking = parent.isImmediatePicking ? true : false;
this.sourceLocations = parent.sourceLocations;
this.destinationLocations = parent.destinationLocations;
// detect if touchscreen (more complicated than one would expect due to browser differences...)
this.istouchSupported = 'ontouchend' in document ||
'ontouchstart' in document ||
'ontouchstart' in window ||
navigator.maxTouchPoints > 0 ||
navigator.msMaxTouchPoints > 0;
},
In _renderLines function,
_renderLines: function () {
//Skipped some codes here
// Render and append the lines, if any.
var $body = this.$el.filter('.o_barcode_lines');
console.log('this model',this.model);
if (this.page.lines.length) {
var $lines = $(QWeb.render('stock_barcode_lines_template', {
lines: this.getProductLines(this.page.lines),
packageLines: this.getPackageLines(this.page.lines),
model: this.model,
groups: this.groups,
isPickingRelated: this.isPickingRelated,
istouchSupported: this.istouchSupported,
}));
$body.prepend($lines);
for (const line of $lines) {
if (line.dataset) {
this._updateIncrementButtons($(line));
}
}
$lines.on('click', '.o_edit', this._onClickEditLine.bind(this));
$lines.on('click', '.o_package_content', this._onClickTruckLine.bind(this));
}
In the above code, you can see this.page.lines field, i need to add my custom two more fields.
Actually it's dead-end for me.
Any solution?

QZ TRAY PRINITING ORDER NOT IN SEQ

I'm trying to print qz tray from javascript.
I have barcode with number in ascending order 1,2,3,4, 5 and so on.
I looping the seq correctly . but when printed out, it was not in order.
setTimeout("directPrint2()",1000);
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
function directPrint2(){
var data;
var xhttp;
var v_carton = "' || x_str_carton ||'";
var carton_arr = v_carton.split('','');
var v1 = "' ||
replace(x_zebra_printer_id, '\', '|') ||
'".replace(/\|/g,"\\");
if(v1 == ""){
alert("Please setup ZPL Printer");
}
else{
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
data = [ toNative(this.responseText) ];
printZPL(data, v1);
}
};
for (var j = 0; j < carton_arr.length; j++){
var url = "' || x_wms_url ||
'WWW_URL.direct_print_label?in_carton_no="+toValidStr(carton_arr[j]);
xhttp.open("GET", url, false);
xhttp.send();
sleep(5000);
}
}
};
',
'javascript'
What's missing from your example:
I do not see any looping logic in the example calling the printZPL function,
printZPL isn't a QZ Tray function and you're missing the code snippet which it calls. Usually this would be qz.print(config, data);.
Regardless of the missing information, the qz.print(...) API is ES6/Promise/A+ based meaning if you want to call qz.print multiple times in a row you need to use a Promise-compatible technique. (e.g. .then(...) syntax) between your print calls as explained in the Chaining Requests guide.
To avoid this, you can concatenate all ZPL data into one large data array. Be careful not to spool too much data at once.
If you know exactly how many jobs you'll be appending, you can hard-code the promise chain:
qz.websocket.connect()
.then(function() {
return qz.printers.find("zebra"); // Pass the printer name into the next Promise
})
.then(function(printer) {
var config = qz.configs.create(printer); // Create a default config for the found printer
var data = ['^XA^FO50,50^ADN,36,20^FDRAW ZPL EXAMPLE^FS^XZ']; // Raw ZPL
return qz.print(config, data);
})
.catch(function(e) { console.error(e); });
Finally, if you do NOT know in advanced how many calls to qz.print(...) you can use a Promise loop as explained in the Promise Loop guide.
function promiseLoop() {
var data = [
"^XA\n^FO50,50^ADN,36,20^FDPRINT 1 ^FS\n^XZ\n",
"^XA\n^FO50,50^ADN,36,20^FDPRINT 2 ^FS\n^XZ\n",
"^XA\n^FO50,50^ADN,36,20^FDPRINT 3 ^FS\n^XZ\n",
"^XA\n^FO50,50^ADN,36,20^FDPRINT 4 ^FS\n^XZ\n"
];
var configs = [
{ "printer": "ZDesigner LP2844-Z" },
{ "printer": "ZDesigner LP2844-Z" },
{ "printer": "ZDesigner LP2844-Z" },
{ "printer": "ZDesigner LP2844-Z" }
];
var chain = [];
for(var i = 0; i < data.length; i++) {
(function(i_) {
//setup this chain link
var link = function() {
return qz.printers.find(configs[i_].printer).then(function(found) {
return qz.print(qz.configs.create(found), [data[i_]]);
});
};
chain.push(link);
})(i);
//closure ensures this promise's concept of `i` doesn't change
}
//can be .connect or `Promise.resolve()`, etc
var firstLink = new RSVP.Promise(function(r, e) { r(); });
var lastLink = null;
chain.reduce(function(sequence, link) {
lastLink = sequence.then(link);
return lastLink;
}, firstLink);
//this will be the very last link in the chain
lastLink.catch(function(err) {
console.error(err);
});
}
Note: The Promise Loop is no longer needed in QZ Tray 2.1. Instead, since 2.1, an array of config objects and data arrays can be provided instead.

rxjs, call next on generator only after previous operation completes

I'm uploading a file by creating slices of file using Blob.slice() in a generator function
export function* chunkFile(file: File, chunkSize: number) {
let chunkStart = 0;
const _chunkEnd = chunkStart + chunkSize;
let chunkEnd = _chunkEnd > file.size ? file.size : _chunkEnd;
while (chunkStart < file.size) {
yield <ChunkType>{
chunk: file.slice(chunkStart, chunkEnd),
start: chunkStart,
end: chunkEnd
};
chunkStart = chunkEnd;
const _chunkEndIn = chunkStart + chunkSize;
chunkEnd = _chunkEndIn > file.size ? file.size : _chunkEndIn;
}
}
and I'm uploading file like this
Observable.from(chunckFile(file,chunkSize)).concatMap(uploadRoutine).subscribe();
But all chunks are created at same time.
what I need is create new chunck (call next on generator) only when current chunk upload completes.
Found Solution by my own
export function rxIterable<T, R>(source: Iterator<T>, consumer: (value: T) => Observable<R>) {
const first = source.next();
if (first.done) {
return empty<R>();
}
return consumer(first.value).pipe(
expand(() => {
const next = source.next();
if (next.done) {
return empty<R>();
}
return consumer(next.value);
}),
finalize(() => source.return())
);
}

Browser loading php script after submitting form using jQuery Form plugin

I'm trying to implement a form using the jQuery Form plugin. The form has three text fields and a file input and I am validating the form in the beforeSend callback. The problem is, whether the validation passes or not, the php script that handles the file upload gets loaded in the browser, which, obviously is not what I want to happen - I need to stay on the form's page.
You can take a look at the form and it's dependent files at http://www.eventidewebdesign.com/public/testUpload/. Indexing is on for that directory, so you can take a look at all of the related files. The form itself is on testUpload.php.
I'd appreciate it if someone could take a look at my code and help me figure out what's going on here.
Please write the following script instead of your, this will work.
<script>
$(document).ready( function() {
// Initialize and populate the datepicker
$('#sermonDate').datepicker();
var currentDate = new Date();
$("#sermonDate").datepicker('setDate',currentDate);
$("#sermonDate").datepicker('option',{ dateFormat: 'mm/dd/yy' });
/*
* Upload
*/
// Reset validation and progress elements
var formValid = true,
percentVal = '0%';
$('#uploadedFile, #sermonTitle, #speakerName, #sermonDate').removeClass('error');
$('#status, #required').empty().removeClass();
$('.statusBar').width(percentVal)
$('.percent').html(percentVal);
$('#frmSermonUpload').ajaxForm({
beforeSend: function() {
if (!ValidateUploadForm()) {
formValid = false;
console.log('validateuploadform returned false');
} else {
console.log('validateuploadform returned true');
formValid = true;
}
console.log('in beforeSend. formValid: ' + formValid);
if (!formValid) {
$('#uploadedFile').val('');
return false;
}
},
uploadProgress: function(event, position, total, percentComplete) {
console.log('in uploadProgress function. formValid: ' + formValid);
if (formValid) {
var percentVal = percentComplete + '%';
$('.statusBar').width(percentVal)
$('.percent').html(percentVal);
}
},
complete: function(xhr) {
console.log('in complete function. formValid: ' + formValid);
if (formValid) {
console.log('xhr.responseText: ' + xhr.responseText);
console.log('formValid: ' + formValid);
if (xhr.responseText === 'success') {
$('.statusBar').width('100%');
$('.percent').html('100%');
$('#status').html('Successfully uploaded the sermon.').addClass('successUpload');
// Clear the form
ClearForm();
} else if (xhr.responseText === 'fail') {
$('#status').html('There was a problem uploading the file. Try again.<br>If the problem persists, contact your system administrator.').addClass('errorUpload');
}
}
}
}); // End Upload Status Bar
});
function ValidateUploadForm() {
// Reset errors and clear message
$('#uploadedFile, #sermonTitle, #speakerName, #sermonDate').removeClass('error');
$('#required').empty();
var result = true;
title = $('#sermonTitle').val(),
speaker = $('#speakerName').val(),
date = $('#sermonDate').val(),
fileName = $('#uploadedFile').val();
extension = $('#uploadedFile').val().split('.').pop().toLowerCase();
//if (fileName !== '' && extension !== 'mp3') {
if ((fileName === '') || (extension !== 'mp3')) {
$('#uploadedFile').addClass('error');
$('#required').html('Only mp3 files are allowed!');
return false;
} else if (fileName === '') {
result = false;
} else if (title === '') {
$('#sermonTitle').addClass('error');
result = false;
} else if (speaker === '') {
$('#speakerName').addClass('error');
result = false;
} else if (date === '') {
$('#sermonDate').addClass('error');
result = false;
}
console.log('returning ' + result + ' from the validateuploadform function');
if (!result) { $('#required').html('All fields are required.'); }
return result;
}
function ClearForm() {
$('#uploadedFile, #sermonTitle, #sermonDate, #speakerName').val('').removeClass();
}
</script>

Win 8 Apps : saving and retrieving data in roamingfolder

I'm trying to store few user data into a roamingFolder method/property of Windows Storage in an app using JavaScript. I'm following a sample code from the Dev Center, but no success. My code snippet is as follows : (OR SkyDrive link for the full project : https://skydrive.live.com/redir?resid=F4CAEFCD620982EB!105&authkey=!AE-ziM-BLJuYj7A )
filesReadCounter: function() {
roamingFolder.getFileAsync(filename)
.then(function (filename) {
return Windows.Storage.FileIO.readTextAsync(filename);
}).done(function (data) {
var dataToRead = JSON.parse(data);
var dataNumber = dataToRead.count;
var message = "Your Saved Conversions";
//for (var i = 0; i < dataNumber; i++) {
message += dataToRead.result;
document.getElementById("savedOutput1").innerText = message;
//}
//counter = parseInt(text);
//document.getElementById("savedOutput2").innerText = dataToRead.counter;
}, function () {
// getFileAsync or readTextAsync failed.
//document.getElementById("savedOutput2").innerText = "Counter: <not found>";
});
},
filesDisplayOutput: function () {
this.filesReadCounter();
}
I'm calling filesDisplayOutput function inside ready method of navigator template's item.js file, to retrieve last session's data. But it always shows blank. I want to save upto 5 data a user may need to save.
I had some trouble running your code as is, but that's tangential to the question. Bottom line, you're not actually reading the file. Note this code, there's no then or done to execute when the promise is fulfilled.
return Windows.Storage.FileIO.readTextAsync(filename);
I hacked this in your example solution and it's working... typical caveats of this is not production code :)
filesReadCounter: function () {
roamingFolder.getFileAsync(filename).then(
function (filename) {
Windows.Storage.FileIO.readTextAsync(filename).done(
function (data) {
var dataToRead = JSON.parse(data);
var dataNumber = dataToRead.count;
var message = "Your Saved Conversions";
//for (var i = 0; i < dataNumber; i++) {
message += dataToRead.result;
document.getElementById("savedOutput1").innerText = message;
//}
//counter = parseInt(text);
//document.getElementById("savedOutput2").innerText = dataToRead.counter;
}, function () {
// readTextAsync failed.
//document.getElementById("savedOutput2").innerText = "Counter: <not found>";
});
},
function () {
// getFileAsync failed
})
},