Script measurement tool in Photoshop to measure distance between two points - photoshop

Can the measurement tool be scripted to measure a custom distance? Not an existing measurement, that is.
I would have thought it possible, but Abobe's documentation are sketchy
and there's not much info when it comes down to scripting the measurement tool. Or ruler, as it use to be known. More specifically a lack of examples using the ruler in a script.
Ideally I'd like to:
Script a measurement from x1,y1 to x2,y2
Determine its length, (preferably from a variable, not from a text file - see below)
Clear the ruler tool (so no ruler line appears)
Delete any measurements (so there are no recordings in the ruler window)
That's basic trig, right? But if you can't set the initial ruler then this is all for nothing.
The only thing on the list I've done is the last. :(
I stumble at the first hurdle not being able to set the ruler, which I thought would be app.activeDocument.recordMeasurements(); Only it gets returned as undefined or Unable to record measurements for selection.
As minimal working, this is pretty minimal:
// Let's stick to pixels as the units to make things easier.
// Switch off any dialog boxes
displayDialogs = DialogModes.ERROR; // OFF
// Get and set the units to pixels
var currentUnits = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;
// delete existing measurements
app.measurementLog.deleteMeasurements(); // THIS WORKS!!
// call the source document
var srcDoc = app.activeDocument;
// Set array to record measurements
var rulerArr = [];
// Set ruler measurement
measure_it(x1,y1,x2,y2); // this a fictional function
// not even the ScriptListener records the ruler tool in a useful form
// var d = app.activeDocument.recordMeasurements(MeasurementSource.MEASURESELECTION, rulerArr); // Unable to record measurements for selection
// var d = app.activeDocument.recordMeasurements(MeasurementSource.MEASURESELECTION); // Unable to record measurements for selection
var d = app.activeDocument.recordMeasurements(); // undefined
var ruler = app.measurementLog; // Is an object!
alert(ruler.length); // undefined
// There's an option to export to a text file
// Is that the only way to get the measurements?
// Can't this be don't internally?
var f = "D:\\temp\\ruler.txt";
ruler.exportMeasurements(f, MeasurementRange.ACTIVEMEASUREMENTS)
alert(app.measurementLog);
// put the units back to how it was
app.preferences.rulerUnits = currentUnits;
// Set Display Dialogs back to normal
displayDialogs = DialogModes.ALL; // NORMAL

Related

Photoshop CC eye dropper tool script

I have a batch action to place a pure white background behind an image. I want to be able to select the color from a fixed pixel position on each photo. When I record the eye dropper in actions it only records the color i picked, not the action of picking the color. I have looked into scripting and tried various solutions on the web.
This is the script I have tried:
var docRef = app.activeDocument;
var pixelLoc = [32,42];
var colorSamplerRef = docRef.colorSamplers.add(pixelLoc);
app.foregroundColor = colorSamplerRef.color;
It doesn't perform the action I need though. Which is select - > color range -> eye dropper tool on fixed position
To achieve this you can create a custom function which invokes the Color Range generated selection, (named selectColorRange in the example gist below).
The selectColorRange function utilizes new ActionDescripter() to configure the properties, which are akin to the settings options shown in the dialog box when you manually choose Select -> Color Range from the Menu bar. This function is invoked after adding the colorSampler at a given x/y coordinate as follows:
selectColorRange(sampledColor, 80); // <-- Specify the fuzziness as required.
Note how we pass in the previous sampledColor value, and a fuzziness value of 80, (which is the default value used in Photoshop).
Example gist:
var docRef = app.activeDocument; // Assumes a document is active.
// Remove any Color Samplers that may already exist.
docRef.colorSamplers.removeAll();
// deselct any selection that may already exist.
docRef.selection.deselect();
// Get color sample from a given x,y coordinate.
var pixelLoc = [32,42];
var colorSampleRef = docRef.colorSamplers.add(pixelLoc);
var sampledColor = colorSampleRef.color;
// Set the foreground color to the sampled color.
app.foregroundColor = sampledColor;
/**
* Invokes and configures `Select > Color Range` from menu bar.
* #param {Object} color - The sampled color object.
* #param {Number} [fuzziness=80] - The Fuziness value (between 0-200).
*/
function selectColorRange(color, fuzziness) {
fuzziness = (typeof fuzziness !== 'undefined') ? fuzziness : 80;
var d1 = new ActionDescriptor();
// Set the amount of Fuzziness.
d1.putInteger(charIDToTypeID('Fzns'), fuzziness);
// Set invert option to false.
d1.putBoolean(charIDToTypeID('Invr'), false);
d1.putInteger(stringIDToTypeID('colorModel'), 0);
// Set the lAB value for Minimum.
var d2 = new ActionDescriptor();
d2.putDouble(charIDToTypeID('Lmnc'), color.lab.l);
d2.putDouble(charIDToTypeID('A '), color.lab.a);
d2.putDouble(charIDToTypeID('B '), color.lab.b);
d1.putObject(charIDToTypeID('Mnm '), charIDToTypeID('LbCl'), d2);
// Set the lAB value for Maximum.
var d3 = new ActionDescriptor();
d3.putDouble(charIDToTypeID('Lmnc'), color.lab.l);
d3.putDouble(charIDToTypeID('A '), color.lab.a);
d3.putDouble(charIDToTypeID('B '), color.lab.b);
d1.putObject(charIDToTypeID('Mxm '), charIDToTypeID('LbCl'), d3);
// Run the Color Range command without showing dialog.
executeAction(charIDToTypeID('ClrR'), d1, DialogModes.NO);
}
// Invoke the function passing in the sample
// color and default fuzziness value.
selectColorRange(sampledColor, 80);
//docRef.selection.clear();
//docRef.selection.fill(app.foregroundColor);
// Remove the Color Sampler.
colorSampleRef.remove();
Additional notes:
Photoshop allows a maximum of four color samplers to be added. If the document already included four color samplers then we'd get an error when attempting to add another one. To avoid the potential of this happening we invoke docRef.colorSamplers.removeAll(); to remove them all first.
Also, to ensure the resultant selection (i.e. the selection created after invoking the selectColorRange function), is not affected by any existing selection(s) we deselect them all first by invoking docRef.selection.deselect();
Finally, the color sampler that we initially added is removed by calling colorSampleRef.remove();
I'm unsure from your question what you intend to to with the selection once it's been created. As an example;
Lets say you wanted to clear the contents of the selection then you'd invoke docRef.selection.clear();.
If you wanted to fill the resultant selection with the previously sampled color then call docRef.selection.fill(app.foregroundColor);

DateTime as ordering key in oxyplot LineSeries

Is there a way to tell oxyplot to use the x value as the connect/draw order for a line plot instead of the order that the points are added?
Let's assume I have this huge amount of points (2Gb in RAM) of a time series. At a higher level I am only adding a small percentage of those points and as the user zooms into a more specific region I add more points to the series so he can see more detail. Almost like a texture mimap. I can add all the points at once but then oxy becomes really slow when I tries to render all those points in a single window in WPF Maybe there is another solution here?
The problem that I am facing is that oxy draws a line from the last point in the graph to the first one of the new batch because it uses the series points list as the draw order not the X value. Is there a way to change this?
Here is a tiny example based on the 'WPF Simple Example':
var plotModel = new PlotModel { Title = "Simple example", Subtitle = "using OxyPlot" };
var timeAxis = new DateTimeAxis
{
Position = AxisPosition.Bottom,
StringFormat = "hh:mm:ss",
};
plotModel.Axes.Add(timeAxis);
var now = DateTime.UtcNow;
// Create two line series (markers are hidden by default)
var series1 = new LineSeries { Title = "Series 1", MarkerType = MarkerType.Circle };
series1.Points.Add(new DataPoint(DateTimeAxis.ToDouble(now), 5));
series1.Points.Add(new DataPoint(DateTimeAxis.ToDouble(now.AddMinutes(1)), 7));
series1.Points.Add(new DataPoint(DateTimeAxis.ToDouble(now.AddMinutes(2)), 8));
series1.Points.Add(new DataPoint(DateTimeAxis.ToDouble(now.AddMinutes(0.5)), 10));
// Add the series to the plot model
plotModel.Series.Add(series1);
// Set the Model property, the INotifyPropertyChanged event will make the WPF Plot control update its content
this.Model = plotModel;
Here is the output, note that the line draws "back in time":
Is there a solution that does not involves me sorting the points list (not even sure if this works)?
Or maybe I am doing this extra points for details thing completely wrong :)

Adobe Photoshop Scripting - How to Select Bounding Box Around Current Selection?

Does anyone know whether it's possible, in Photoshop extend script, to convert an irregular selection (e.g. magic wand tool selection) into a rectangular selection encompassing the top, left, bottom and right bounds of the selection?
Here it is, I have documented the code so you can modify it later if you need. Also, check page 166 and following of Photoshop's JS reference manual, you may read more about selections - you can set feather, extend/intersect/etc. the selection if you need to.
Made for CS6, should work with latter.
#target photoshop
if (documents.length == 0) {
alert("nothing opened");
} else {
// start
//setup
var file = app.activeDocument;
var selec = file.selection;
//run
var bnds = selec.bounds; // get the bounds of current selection
var // save the particular pixel values
xLeft = bnds[0],
yTop = bnds[1],
xRight = bnds[2],
yBottom = bnds[3];
var newRect = [ [xLeft,yTop], [xLeft,yBottom], [xRight,yBottom], [xRight,yTop] ]; // set coords for selection, counter-clockwise
selec.deselect;
selec.select(newRect);
// end
}

constrain proportions while resizing images

I implemented drag and drop of images and now i want to constrain proportions of images while resizing.
/**
* Variable: constrainChildrenOnResize
*
* Specifies if children should be constrained according to the <constrainChildren>
* switch if cells are resized (including via <foldCells>). Default is false for
* backwards compatiblity.
*/
mxGraph.prototype.constrainChildrenOnResize = false;
i set this to true but its not working :s
What API/property i need for this functionality..
constrainChildrenOnResize is responsible for positioning and size of the children of resized cell. It means that children should keep their position relatively to the parent-cell.
In your case I would suggest to extend mxVertexHandler using union method. In this example you can see how to implement min-width/min-height restrictions. Using this example you are able to write your own rules for constrain.
Here is my simple solution:
var vertexHandlerUnion = mxVertexHandler.prototype.union;
mxVertexHandler.prototype.union = function (bounds) {
var result = vertexHandlerUnion.apply(this, arguments);
var coff = bounds.width / bounds.height
result.width = result.height * coff;
return result;
};
So this function is called every time you move mouse during dragging the resizer.
bounds - object, always same and represent old geometry of the cell (before resizing)
result - object, represents new values, which are going to be applied. Between this line ad return statement you can place any code you need to modify result.
In my simple example I just get the initial relation between width and height of the cell (coff) and then set new width by multiplying coff and new height. It will work if you drag corner or top/bottom. In real project this logic should be slightly extended, or you should make visible only corner handlers.
By the way, this code will work for all resizable cells on your graph. If you want to apply it only to images or some other kind of cells - you can put condition and check the cell type before recalculating. You can get current cell or its state via this.state.cell or this.state inside of union function.
For example only for vertecies:
... ...
var result = vertexHandlerUnion.apply(this, arguments);
if (this.state.cell.isVertex()) {
//calculations here
}
return result;

Add flat amount to canvas size

I want to have some automated process (either action or script) that will copy selection(assumes something has already been selected), place in new canvas, increase canvas size by exactly 10 pixels in height & width, then save it to the desktop.
I'm currently using an action and it works correctly with the exception of the 10 pixels part. I can do something like 10% by using the percentage adjustment in the canvas size menu, but I can't figure out how to do exactly 10 pixels. During the recording, if I just increase the canvas size by 10 pixels it'll record that exact amount (say it was 100x100, it records that I resized canvas to 110x100). So when I play that action on a selection that's of size 50x50 it resizes it to 110x110.... So the problem is that the action records the literal value of the canvas resize and not the add 10 pixels part...
Any ideas here?
This can be scripted as well, but if you've already got an action set up, try modifying your action to do the following:
paste the selection into new document larger than you expect to ever require
expand the selection by 10 px
crop the document to the selection
save
Or, to script it you can tweak the following sample. It assumes you have already copied your image to the clipboard:
#target photoshop
app.preferences.rulerUnits = Units.PIXELS;
app.preferences.typeUnits = TypeUnits.PIXELS;
var doc = app.documents.add('1000px');
var lyr = doc.artLayers.add();
doc.activeLayer = lyr;
doc.paste ();
var bnds = lyr.bounds;
var unitsToAdd = new UnitValue(10, 'px');
bnds[0] = bnds[0] - unitsToAdd;
bnds[1] = bnds[1] - unitsToAdd;
bnds[2] = bnds[2] + unitsToAdd;
bnds[3] = bnds[3] + unitsToAdd;
doc.crop(bnds) ;
doc.saveAs(new File('/c/temp/temp.psd'));