![]() |
| |||||||
| Photoshop Scripting Learning and sharing for all platforms |
| | LinkBack | Thread Tools |
|
#1
| |||
| |||
| Script to center-crop images to a fixed ratio My objective is to iterate thru a folder of images, center crop the images based on height/width ratio variables, and save the images within the same folder. I've detailed the 2 IF statements conditionals below- On all the calculations, round up to the nearest pixel. Code: Variables: WidthRatio = 4 HeightRatio = 3 -- Image's aspect ratio is greater than the desired ratio -- so crop out left and right areas of the Image If (Image's width / Image's height) > (WidthRatio/ HeightRatio) Set selection To: rectangle Top: 0 px Left: (Image's width - (Image's height * (WidthRatio/HeightRatio))) / 2 px Bottom: (Image's height) px Right: (Image's width + (Image's height * (WidthRatio/HeightRatio))) / 2 px Crop Save image End If -- Image's aspect ratio is less than the desired ratio -- so crop out top and bottom areas of the Image If (Image's width / Image's height) < (WidthRatio/ HeightRatio) Set selection To: rectangle Top: (Image's height - (Image's width * (HeightRatio/WidthRatio))) / 2 px Left: 0 px Bottom: (Image's height + (Image's width * (HeightRatio/WidthRatio))) / 2 px Right: (Image's width) px Crop Save image End If Dan |
|
#2
| ||||
| ||||
| Re: Script to center-crop images to a fixed ratio Hi Dan: Yep...this would need a script and FWIW it's way over my head scripting wise (I'm a rookie at this). In addition to RetouchPRO there are two other places where I post questions of this nature. If you haven't yet, I highly recommend you check them out: * http://www.ps-scripts.com * http://www.adobe.com - Support, Photoshop scripting forum |
|
#3
| |||
| |||
| Re: Script to center-crop images to a fixed ratio Fyi I got it work using this script: Code: // Get the active document and make a new selection.
// enable double clicking from the Macintosh Finder or the Windows Explorer
#target photoshop
// in case we double clicked the file
app.bringToFront();
// debug level: 0-2 (0:disable, 1:break on error, 2:break at beginning)
// $.level = 0;
// debugger; // launch debugger on next line
if (app.documents.length > 0) {
var docRef = app.activeDocument;
var WidthRatio = 4;
var HeightRatio = 3;
var boundTop;
var boundLeft;
var boundRight;
var boundBottom;
// Image's aspect ratio is greater than the desired ratio
// so crop out left and right areas of the Image
if ((docRef.width / docRef.height) > (WidthRatio/ HeightRatio))
{
boundTop = 0;
boundLeft = ((docRef.width - (docRef.height * (WidthRatio/HeightRatio))) / 2);
boundBottom = docRef.height;
boundRight = ((docRef.width + (docRef.height * (WidthRatio/HeightRatio))) / 2);
bounds = new Array(boundLeft,boundTop,boundRight,boundBottom);
docRef.crop(bounds);
}
// Image's aspect ratio is less than the desired ratio
// so crop out top and bottom areas of the Image
if ((docRef.width / docRef.height) < (WidthRatio/ HeightRatio))
{
boundTop = ((docRef.height - (docRef.width * (HeightRatio/WidthRatio))) / 2);
boundLeft = 0;
boundBottom = ((docRef.height + (docRef.width * (HeightRatio/WidthRatio))) / 2);
boundRight = docRef.width;
bounds = new Array(boundLeft,boundTop,boundRight,boundBottom);
docRef.crop(bounds);
}
// bounds = new Array(10, 10, app.activeDocument.width - 10, app.activeDocument.height - 10);
// docRef.crop(bounds);
boundTop = null;
boundLeft = null;
boundRight = null;
boundBottom = null;
WidthRatio = null;
HeightRatio = null;
docRef = null;
}
|
|
#4
| ||||
| ||||
| Re: Script to center-crop images to a fixed ratio Well done. Thanks for sharing your solution. Under what version of PS did you write this script? Reason I ask: There are subtle syntax differences between versions. |
|
#5
| |||
| |||
| Re: Script to center-crop images to a fixed ratio The script works with CS3 (haven't tested any other versions). Thanks |
|
#6
| |||
| |||
| Re: Script to center-crop images to a fixed ratio I am a total newbie to photoshop scripts altogether, and I came across this thread in a google search following a similar issue. I have a very nice collection of high-resolution desktop wallpapers for full-screen monitors and I'm upgrading to a new 1680x1050 LCD.. I would like to rig up a script along these lines to crop to a ratio of 16 by 10 and save them in a folder called "Widescreen", basically the opposite of what Dan here is trying to do - I looked over on the Adobe page as well and actually found his similar post there. So Dan yourself, maybe you can shoot me a PM on how to put this into a working file and then how to use it with ps3? Thanks in advance.. |
|
#7
| ||||
| ||||
| Re: Script to center-crop images to a fixed ratio Hi Momono, don't make this more difficult than it needs to be - you can easily do this with a Photoshop action. |
|
#8
| |||
| |||
| Re: Script to center-crop images to a fixed ratio And how would I begin to do that? I've tinkered around with it and there doesn't seem to be an aspect ratio crop option in the normal menu stuff.. I put the working code provided here into a script that did what it said it would, it just didn't save it or run the whole batch, just cropped to the aspect I put in for the one file. |
|
#9
| ||||
| ||||
| Re: Script to center-crop images to a fixed ratio Just record: 1. File > Automate > Fit Image ... set to 1680px wide 2. Image > Canvas Size ... set to 1050px high 3. Sharpen 4. Save and close Then run that action in a batch, or via File > Scripts > Image Processor |
|
#10
| ||||
| ||||
| Re: Script to center-crop images to a fixed ratio Quote:
Note **: > 1280x1024 will result in 1680x1345 > 1600x1200 will result in 1680x1261 ... after applying Fit Image command, so the following Canvas Size command will "cut off" little at the top and bottom of each file. ** Image source sizes provided to me in a PM from momono. When the Canvas Size command is applied, PS will display an "Are you sure?" warning that must be acknowledged = this will not a "hands off"/automatic solution even if recorded in an action applied though euther Automate > Batch or Automate > Scripts > Image Processor. No free lunch in this one... PM me if you need help on recording the action or applying it. |
|
#11
| |||
| |||
| Re: Script to center-crop images to a fixed ratio Hey guys, thanks for the replies. The action recording did it - but in order to do the 'fit image' command I had to figure out the 4/3 constituent of the 1680 width (which is 1260), then do the crop command (with both h and w data) - and instead of applying the sharpen filter like suggested, I did a one-pixel motion blur instead... for the 1600x1200 images I have this turns the trick, and now so far I have a beautiful little collection of 1680x1050 frogs and nebulae.. Lemme know how many of you widescreen-toting photoshop gurus want somma this candy! Thanks again, - Brendan |
|
#12
| ||||
| ||||
| Re: Script to center-crop images to a fixed ratio FWIW - I thought to try it in IrfanView. Using 2592 x 1944 images I batch cropped with the following settings: X-pos 456 <<- (2592-1680)/2=456 Y-pos 447 <<- (1944-1050)/2=447 Width 1680, Height 1050, Start Corner: Left Top Juergen |
|
#13
| ||||
| ||||
| Re: Script to center-crop images to a fixed ratio Would FastStone Photo Resizer 2.7 Freeware (Last Update: 2008-10-07) work for your project? |
|
#14
| ||||
| ||||
| Re: Script to center-crop images to a fixed ratio It looks like FastStone lets you input the same settings as I used in IrfanView. It should work the same. Juergen |
|
#15
| |||
| |||
| Re: Script to center-crop images to a fixed ratio Thanks for all the suggestions guys, they probably all work but I got this one pretty much licked in photoshop and learned a few things to boot with your help.. The best solution seems to be loading that code supplied by gct13 into a script file and saving it, opening one of the pictures and starting a new action record, run that script (tweaked to the new ratio 8:5), then resize it to 1680x1050 in my case and then maybe add a 1 pixel blur. Then I stop recording, go to the scripts - image processor and select the source folder, pick the action I made from the list, make it so it saves the new ones in the same folder (makes a new folder called JPEG, whatever) and just do that for folder after folder.. The fit image method ended up with some of my wallpapers having about 75 pixels of white gapping on either side.. Soo I'm of the opinion that God made LCD monitors for insanely high-res vistas and microcosms of the awesomeness of the Universe and this planet.. So here is the absolute best wallpaper site I have ever found, bar none.. probably familiar to a few of you - www.naturedesktop.org .. Just scroll down the page a little to find your resolution.. Each res has a different set of unique stuff, some carryovers, but all incredible.. but this little trick can now open any resolution to another pretty much. I'm now on file 299 / 1015 in the 1920 res's.. I harvest huge folders and load them into Webshots 1.0 (2 and beyond have spyware) with the camera turned off.. I'm a freelance computer repair guy and when I do a new format of Windows I include these webshots packs according to the screen size of my customers. They seem to enjoy it! Well anyway, thanks again, lemme know if anybody wants more links to this stuff. Peace. |
|
#16
| |||
| |||
| Re: Script to center-crop images to a fixed ratio This may be a super dumb question, but the script presented by GCT13, how do I take that and use that in Photoshop? I have only worked with actions in photoshop, never scripts? What are the steps to taking what GCT13 posted and turn it into something I can use in PS-CS3? |
|
#17
| |||
| |||
| Re: Script to center-crop images to a fixed ratio Hello Mr. Jones! It's actually a good question, because it's the same one I was asking of these guys and didn't really get an answer, and in the end I had to figure it out myself.. You would open a fresh new txt file, paste in the provided code, change the variables for the crop to your suiting and save it as a 'whatever.jsx' file (change file type to 'all files') in your work folder or wherever you can remember it.. then start a new action record in photoshop, doing everything I described in my last post. Also I discovered that for images less than the desired resolution (such as 1600x1200 for example, still good enough imho) you should resize the image to 1680 width (if that happens to be your desired resolution) relative to whatever aspect ratio your source is *before* you run the script to crop - if you don't do this it seems that images that start at a lower resolution or an odd res like 1280x960 end up with white bars on either side after you run an image batch using the action you've recorded. Hope that helps.. |
|
#18
| |||
| |||
| Re: Script to center-crop images to a fixed ratio GCT13, how would you change that script to make the document 2000x2000 as well as being able to center the image and have it line up at a specific X coordinate? |
|
#19
| |||
| |||
| Re: Script to center-crop images to a fixed ratio This script can make any aspect ratio selection you want can be centered rectangle or oval be feather etc. It is a Photoshop Plug-in and will be listed in the Photoshop menu File>Automate>Aspect Ratio Selection. Can be used while recording an action and the values used in the scripts dialog will be recorded and used when the action is played. AspectRatioSelection.jsx Code: /* ==========================================================
// Christmass 2007 John J. McAssey (JJMack) and the
// Day I descovered Photoshop had what I wanted
// a way to pass Prams to Scripts throught menu File>Automate
// ======================================================= */
/* Special properties for a JavaScript to enable it to behave like an automation plug-in, the variable name must be exactly
as the following example and the variables must be defined in the top 1000 characters of the file
// BEGIN__HARVEST_EXCEPTION_ZSTRING
<javascriptresource>
<name>$$$/JavaScripts/AspectRatioSelection/Name=Aspect Ratio Selection...</name>
<about>$$$/JavaScripts/AspectRatioSelection/About=Aspect Ratio Selection Version 0.0 By JJmack a Hacker use at your own risk Quality forget about it.</about>
<menu>automate</menu>
<enableinfo>true</enableinfo>
<eventid>3caa3434-cb67-11d1-bc43-0060b0a13dc5</eventid>
</javascriptresource>
// END__HARVEST_EXCEPTION_ZSTRING
*/
/* ===========================================================================================================
// I'm useng the same <eventid>3caa3434-cb67-11d1-bc43-0060b0a13dc4</eventid> as Fit Image right now ?????
// Using the same ID broke the resize function of the Image Processor so I changed the last 4 to 5
// Fit Image.jsx and Conditional Mode Change.jsx have the same /Events and /Enum so I copied these also ????
// Also the save pram use sizeInfo and a strange string to "8090f848-cc6b-44a2-ae17-fbe01d5b9630"
// I change name of my info to arInfo and the strange string to "8090f848-cc6b-44a2-ae17-fbe01d5b963a"
// Did not find these strings is the windows registry
// ============================================================================================================ */
/*
/* Adapt Fit Image code for my own Automate Script */
/* enable double clicking from the Macintosh Finder or the Windows Explorer */
#target photoshop
// debug level: 0-2 (0:disable, 1:break on error, 2:break at beginning)
// $.level = 1;
// debugger; // launch debugger on next line
var showparms = false;
// on localized builds we pull the $$$/Strings from a .dat file, see documentation for more details
$.localize = true;
var isCancelled = true; // assume cancelled until actual resize occurs
/* The main routine ============================================================================================
// AspectRatioSelection object does most of the work
// ============================================================================================================= */
try {
GlobalVariables();
// ============================================================================================================
// Reset Vars Used and create some alias to make things easier for this hacker
// ============================================================================================================ */
var type = "None Set";
var shape = "None Set";
// vars for shape
var rectangle ="Rctn";
var ellipse ="Elps";
// vars for type
var diminish =SelectionType.DIMINISH
var subtract =SelectionType.DIMINISH
var extend =SelectionType.EXTEND
var add =SelectionType.EXTEND
var intersect =SelectionType.INTERSECT
var replace =SelectionType.REPLACE
/* ============================================================================================================
// end vars and Aliases
// ============================================================================================================ */
CheckVersion();
// create our default params
var arInfo = new ARInfo();
if (showparms) {
alert( "Inital State" + " " +
"Center " + FLAG_CENTER + " " + arInfo.flagCENTER +
" Border " + FLAG_BORDER + " " + arInfo.flagBORDER +
" Anti_Alias " + FLAG_ANTIALIAS + " " + arInfo.flagANTIALIAS +
" Rectantangle " + FLAG_RECTANGLE + " " + arInfo.flagRECTANGLE +
" Ellipse " + FLAG_ELLIPSE + " " + arInfo.flagELLIPSE +
" Replace " + FLAG_REPLACE + " " + arInfo.flagREPLACE +
" Add " + FLAG_ADD + " " + arInfo.flagADD +
" Substract " + FLAG_SUBTRACT + " " + arInfo.flagSUBTRACT +
" Intersect " + FLAG_INTERSECT + " " + arInfo.flagINTERSECT); }
if (showparms) {alert("start " + arInfo.width.value + ":" + arInfo.height.value + " Center " + FLAG_CENTER + " Border " + FLAG_BORDER +" Shape " + shape + " Selection Type " + type + " Feather " + arInfo.feather.value + " Anti-Alias " + FLAG_ANTIALIAS); }
var gIP = new AspectRatioSelection();
if ( DialogModes.ALL == app.playbackDisplayDialogs ) {
gIP.CreateDialog();
gIP.RunDialog();
}
else {
// This is what does the script with values saved in actions
gIP.InitVariables();
if (showparms) {
alert( "Action State" + " " +
"Center " + FLAG_CENTER + " " + arInfo.flagCENTER +
" Border " + FLAG_BORDER + " " + arInfo.flagBORDER +
" Anti_Alias " + FLAG_ANTIALIAS + " " + arInfo.flagANTIALIAS +
" Rectantangle " + FLAG_RECTANGLE + " " + arInfo.flagRECTANGLE +
" Ellipse " + FLAG_ELLIPSE + " " + arInfo.flagELLIPSE +
" Replace " + FLAG_REPLACE + " " + arInfo.flagREPLACE +
" Add " + FLAG_ADD + " " + arInfo.flagADD +
" Substract " + FLAG_SUBTRACT + " " + arInfo.flagSUBTRACT +
" Intersect " + FLAG_INTERSECT + " " + arInfo.flagINTERSECT); }
if (showparms) {alert("From Action " + arInfo.width.value + ":" + arInfo.height.value + " Center " + FLAG_CENTER + " Border " + FLAG_BORDER +" Shape " + shape + " Selection Type " + type + " Feather " + arInfo.feather.value + " Anti-Alias " + FLAG_ANTIALIAS ); }
ARselect(arInfo.width.value, arInfo.height.value, FLAG_CENTER, FLAG_BORDER, shape, type, arInfo.feather.value, FLAG_ANTIALIAS );
}
if (!isCancelled) {
SaveOffParameters(arInfo);
}
}
// Lot's of things can go wrong
// Give a generic alert and see if they want the details
catch( e ) {
if ( DialogModes.NO != app.playbackDisplayDialogs ) {
alert( e + " : " + e.line );
}
}
// restore the dialog modes
app.displayDialogs = gSaveDialogMode;
isCancelled ? 'cancel' : undefined;
/* ==================================================================================================================================================
================================================================================================================================================== */
function ARselect(width, height, center, border, shape, type, feather, antiAlias ) {
// prepare the ruler
var defaultRulerUnits = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;
var originalheight = app.activeDocument.height.value;
var originalwidth = app.activeDocument.width.value;
// ====================================================================================================== //
// Calculate Top Left Corner x1 y1 Bottom Left Corner x2 y2 for aspectratio + origin for avtive document //
// ====================================================================================================== //
if ( height>width ) { aspectRatio = height/width;
} else {aspectRatio = width/height;}
if (originalheight>originalwidth) {
// Portraits
originalAspectRatio = originalheight/originalwidth;
if (originalAspectRatio < aspectRatio) {
// Current aspect ratio less trim width
x1 = 0;
y1 = 0;
x2 = Math.round(originalheight/aspectRatio);
y2 = originalheight;
if ( center ) {
x1 = Math.round(originalwidth-x2)/2;
x2 += Math.round(originalwidth-x2)/2;
}
} else {
// Current aspect not less trim height
x1 = 0;
y1 = 0;
x2 = originalwidth;
y2= Math.round(originalwidth*aspectRatio);
if ( center ) {
y1 = Math.round(originalheight-y2)/2;
y2 += Math.round(originalheight-y2)/2;
}
}
} else {
// Landscapes including square
originalAspectRatio = originalwidth/originalheight
if (originalAspectRatio < aspectRatio) {
// Current aspect ratio less trim height
x1 = 0;
y1 = 0;
x2 = originalwidth;
y2 = Math.round(originalwidth / aspectRatio);
if ( center ) {
y1 = Math.round(originalheight-y2)/2;
y2 += Math.round(originalheight-y2)/2;
}
} else {
// Current aspect not less trim width
x1 = 0;
y1 = 0;
x2= Math.round(originalheight*aspectRatio);
y2 = originalheight;
if ( center ) {
x1 = Math.round(originalwidth-x2)/2;
x2 += Math.round(originalwidth-x2)/2;
}
}
}
if (border) {
xBorder = Math.round(x2-x1)*.25/2;
yBorder = Math.round(y2-y1)*.25/2;
x1 = x1+xBorder;
x2 = x2-xBorder;
y1 = y1+yBorder;
y2 = y2-yBorder;
}
// Set Marquee Selection Top Left and Bottom Right corners (x1, y1, x2, y2);
setMarqueeSelection(x1, y1, x2, y2, type, shape, feather, antiAlias);
// restore the ruler to whatever unit it was in
app.preferences.rulerUnits = defaultRulerUnits;
isCancelled = false; // if get here, definitely executed
return false; // no error
}
/* SetMarqueeSelection function from Scriptlistner plugin
// ========================================================================== */
function setMarqueeSelection(x1, y1, x2, y2, type, shape, feather, antiAlias) {
var SelectionType =null;
if (type ==null) { var SelectionType = "setd" }
if (type ==diminish) { var SelectionType = "SbtF" }
if (type ==extend) { var SelectionType = "AddT" }
if (type ==intersect) { var SelectionType = "IntW" }
if (type ==replace) { var SelectionType = "setd" }
var id3 = charIDToTypeID( SelectionType );
var desc2 = new ActionDescriptor();
var id4 = charIDToTypeID( "null" );
var ref1 = new ActionReference();
var id5 = charIDToTypeID( "Chnl" );
var id6 = charIDToTypeID( "fsel" );
ref1.putProperty( id5, id6 );
desc2.putReference( id4, ref1 );
var id7 = charIDToTypeID( "T " );
var desc3 = new ActionDescriptor();
var id8 = charIDToTypeID( "Top " );
var id9 = charIDToTypeID( "#Pxl" );
desc3.putUnitDouble( id8, id9, y1 );
var id10 = charIDToTypeID( "Left" );
var id11 = charIDToTypeID( "#Pxl" );
desc3.putUnitDouble( id10, id11, x1 );
var id12 = charIDToTypeID( "Btom" );
var id13 = charIDToTypeID( "#Pxl" );
desc3.putUnitDouble( id12, id13, y2 );
var id14 = charIDToTypeID( "Rght" );
var id15 = charIDToTypeID( "#Pxl" );
desc3.putUnitDouble( id14, id15, x2 );
var id16 = charIDToTypeID( shape );
desc2.putObject( id7, id16, desc3 );
var id17 = charIDToTypeID( "Fthr" );
var id18 = charIDToTypeID( "#Pxl" );
desc2.putUnitDouble( id17, id18, feather );
var id19 = charIDToTypeID( "AntA" );
desc2.putBoolean( id19, antiAlias );
executeAction( id3, desc2, DialogModes.NO );
}
/* ==================================================================================================================================================
================================================================================================================================================== */
// created in
function SaveOffParameters(arInfo) {
// save off our last run parameters
var d = objectToDescriptor(arInfo);
d.putString( app.charIDToTypeID( 'Msge' ), strMessage );
app.putCustomOptions("8090f848-cc6b-44a2-ae17-fbe01d5b963a", d);
app.playbackDisplayDialogs = DialogModes.ALL;
// save off another copy so Photoshop can track them corectly
var dd = objectToDescriptor(arInfo);
dd.putString( app.charIDToTypeID( 'Msge' ), strMessage );
app.playbackParameters = dd;
}
/* ==================================================================================================================================================
================================================================================================================================================== */
function GlobalVariables() {
// a version for possible expansion issues
gVersion = 1;
// remember the dialog modes
gSaveDialogMode = app.displayDialogs;
app.displayDialogs = DialogModes.NO;
// all the strings that need to be localized
strTitle = localize( "$$$/JavaScript/AspectRatioSelection/Title=Aspect Ratio Selection" );
strAspectRatio = localize( "$$$/JavaScript/AspectRatioSelection/AspectRatio=Aspect Ratio" );
strTextWidth = localize("$$$/JavaScripts/AspectRatioSelection/Width=&Width:");
strTextHeight = localize("$$$/JavaScripts/AspectRatioSelection/Height=&Height:");
strTextNumber = localize("$$$/JavaScripts/AspectRatioSelection/Number=Number");
strTextColen = localize("$$$/JavaScripts/AspectRatioSelection/Colen=:");
strTextSelectionOptions = localize("$$$/JavaScripts/AspectRatioSelection/SelectionOptions=Selection Options");
strChkCenter = localize("$$$/JavaScripts/AspectRatioSelection/ChkCenter=&Center");
strChkBorder = localize("$$$/JavaScripts/AspectRatioSelection/ChkBorder=&Border");
strTextShapeType = localize("$$$/JavaScripts/AspectRatioSelection/ShapeType=Shape Type");
strTextRectangle = localize("$$$/JavaScripts/AspectRatioSelection/Rectangle=Rectangle");
strTextEllipse = localize("$$$/JavaScripts/AspectRatioSelection/Ellipse=Ellipse");
strTextSelectionType = localize("$$$/JavaScripts/AspectRatioSelection/SelectionType=Selection Type");
strTextReplace = localize("$$$/JavaScripts/AspectRatioSelection/Replace=Replace");
strTextAdd = localize("$$$/JavaScripts/AspectRatioSelection/Add=Add");
strTextSubtract = localize("$$$/JavaScripts/AspectRatioSelection/Substrac=Substract");
strTextIntersect = localize("$$$/JavaScripts/AspectRatioSelection/Intersect=Intersect");
strTextFeatherAmount = localize("$$$/JavaScripts/AspectRatioSelection/FeatherAmount=Feather Amount");
strTextPixels = localize("$$$/JavaScripts/AspectRatioSelection/Pixels=Pixels");
strTextAnitAlias = localize("$$$/JavaScripts/AspectRatioSelection/AntiAlias=Anti-Alias");
strChkAnitAlias = localize("$$$/JavaScripts/AspectRatioSelection/ChkAntiAlias=&Anti-Alias");
strButtonOK = localize("$$$/JavaScripts/AspectRatioSelection/OK=OK");
strButtonCancel = localize("$$$/JavaScripts/AspectRatioSelection/Cancel=Cancel");
strTextSorry = localize("$$$/JavaScripts/AspectRatioSelection/Sorry=Sorry, Dialog failed");
strTextInvalidType = localize("$$$/JavaScripts/AspectRatioSelection/InvalidType=Invalid numeric value");
strTextInvalidNum = localize("$$$/JavaScripts/AspectRatioSelection/InvalidNum=A number between 1 and 30000 is required. Closest value inserted.");
strTextNeedFile = localize("$$$/JavaScripts/AspectRatioSelection/NeedFile=You must have a file selected before using Aspect Ratio Selection");
strMessage = localize("$$$/JavaScripts/AspectRatioSelection/Message=Aspect Ratio Selection action settings");
strMustUse = localize( "$$$/JavaScripts/AspectRatioSelection/MustUse=You must use Photoshop CS 3 or later to run this script!" );
strHelpAR = localize( "$$$/JavaScripts/AspectRatioSelection/AR=Aspect Ratio width and height" );
strHelpCTR = localize( "$$$/JavaScripts/AspectRatioSelection/CTR=Origin Center or Top Left" );
strHelpBRD = localize( "$$$/JavaScripts/AspectRatioSelection/BRD=25% border or not" );
strHelpRCT = localize( "$$$/JavaScripts/AspectRatioSelection/RCT=Select a rectangle" );
strHelpEPS = localize( "$$$/JavaScripts/AspectRatioSelection/EPS=Select an ellipse" );
strHelpRPL = localize( "$$$/JavaScripts/AspectRatioSelection/RPL=Replace current selection or make new one" );
strHelpADD = localize( "$$$/JavaScripts/AspectRatioSelection/ADD=Add to current selection" );
strHelpSUB = localize( "$$$/JavaScripts/AspectRatioSelection/SUB=Subtract from crrent selection" );
strHelpINT = localize( "$$$/JavaScripts/AspectRatioSelection/INT=Intersect with current selection" );
strHelpFTR = localize( "$$$/JavaScripts/AspectRatioSelection/FTR=Number of pixels to feather by" );
strHelpANT = localize( "$$$/JavaScripts/AspectRatioSelection/ANT=Anti-Alias or not" );
// bit flags for checkboxes
FLAG_CENTER = false;
FLAG_BORDER = false;
FLAG_ANTIALIAS = false;
// bit flags for radiobuttons
FLAG_RECTANGLE = false;
FLAG_ELLIPSE = false;
FLAG_REPLACE = false;
FLAG_ADD = false;
FLAG_SUBTRACT = false;
FLAG_INTERSECT = false;
}
/* ================================================== The main class ==================================================================================== */
function AspectRatioSelection() {
this.CreateDialog = function() {
// I will keep most of the important dialog items at the same level
// and use auto layout
// use overriding group so OK/Cancel buttons placed to right of panel
var res =
"dialog { \
pAndB: Group { orientation: 'column', \
arinfo: Panel { orientation: 'row', borderStyle: 'sunken', \
text: '" + strAspectRatio +"', \
helpTip: '" + strHelpAR + "',\
w: Group { orientation: 'row', alignment: 'right',\
helpTip: '" + strHelpAR + "',\
s: StaticText { text:'"+"' }, \
e: EditText { preferredSize: [45, 20] }, \
p: StaticText { text:'" + strTextNumber +"'} \
}, \
h: Group { orientation: 'row', alignment: 'right', \
helpTip: '" + strHelpAR + "',\
s: StaticText { text:'" + strTextColen + "' }, \
e: EditText { preferredSize: [45, 20] }, \
p: StaticText { text:'" + strTextNumber + "'} \
} \
}, \
opinfo: Panel { orientation: 'row', borderStyle: 'sunken', \
text: '" + strTextSelectionOptions +"', \
helpTip: '" + strHelpCTR + ", " + strHelpBRD + "',\
ctr: Checkbox { text:'" + strChkCenter +"', alignment:'left'}, \
bdr: Checkbox { text:'" + strChkBorder + "', alignment:'left'} \
}, \
shinfo: Panel { orientation: 'row', borderStyle: 'sunken', \
text: '" + strTextShapeType +"', \
helpTip: '" + strHelpRCT + ", " + strHelpEPS + "',\
rct: RadioButton { text:'" + strTextRectangle +"', alignment:'left'}, \
eps: RadioButton { text:'" + strTextEllipse + "', alignment:'left'} \
}, \
tyinfo: Panel { orientation: 'row', borderStyle: 'sunken', \
text: '" + strTextSelectionType +"', \
helpTip: '" + strHelpRPL + ", " + strHelpADD + ", " + strHelpSUB + ", " + strHelpINT + "',\
rpl: RadioButton { text:'" + strTextReplace +"', alignment:'left'}, \
adr: RadioButton { text:'" + strTextAdd +"', alignment:'left'}, \
sub: RadioButton { text:'" + strTextSubtract +"', alignment:'left'}, \
itc: RadioButton { text:'" + strTextIntersect + "', alignment:'left'} \
}, \
ftinfo: Panel { orientation: 'row', borderStyle: 'sunken', \
text: '" + strTextFeatherAmount +"', \
helpTip: '" + strHelpFTR + "',\
f: Group { orientation: 'row', alignment: 'right',\
helpTip: '" + strHelpFTR + "',\
s: StaticText { text:'"+"' }, \
e: EditText { preferredSize: [45, 20] }, \
p: StaticText { text:'" + strTextPixels +"'} \
} \
}, \
aainfo: Panel { orientation: 'row', borderStyle: 'sunken', \
text: '" + strTextAnitAlias +"', \
helpTip: '" + strHelpANT + "',\
ant: Checkbox { text:'" + strChkAnitAlias + "', alignment:'left'} \
}, \
buttons: Group { orientation: 'row', alignment: 'top', \
okBtn: Button { text:'" + strButtonOK +"', properties:{name:'ok'} }, \
cancelBtn: Button { text:'" + strButtonCancel + "', properties:{name:'cancel'} } \
} \
} \
}";
// the following, when placed after e: in w and h doesn't show up
// this seems to be OK since px is put inside the dialog box
//p: StaticText { text:'" + strTextPixels + "'}
// create the main dialog window, this holds all our data
this.dlgMain = new Window(res,strTitle);
// create a shortcut for easier typing
var d = this.dlgMain;
d.defaultElement = d.pAndB.buttons.okBtn;
d.cancelElement = d.pAndB.buttons.cancelBtn;
} // end of CreateDialog
/* ==================================================================================================================================================
================================================================================================================================================== */
// initialize variables of dialog
this.InitVariables = function() {
var oldPref = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;
// look for last used params via Photoshop registry, getCustomOptions will throw if none exist
try {
var desc = app.getCustomOptions("8090f848-cc6b-44a2-ae17-fbe01d5b963a");
descriptorToObject(arInfo, desc);
}
catch(e) {
// it's ok if we don't have any options, continue with defaults
}
// see if I am getting descriptor parameters
descriptorToObject(arInfo, app.playbackParameters);
// make internal state reflect saved parameters
FLAG_CENTER = arInfo.flagCENTER;
FLAG_BORDER = arInfo.flagBORDER;
FLAG_ANTIALIAS = arInfo.flagANTIALIAS;
FLAG_RECTANGLE = arInfo.flagRECTANGLE;
FLAG_ELLIPSE = arInfo.flagELLIPSE;
FLAG_REPLACE = arInfo.flagREPLACE;
FLAG_ADD = arInfo.flagADD;
FLAG_SUBTRACT = arInfo.flagSUBTRACT;
FLAG_INTERSECT = arInfo.flagINTERSECT;
// Use Radio button settings
if ( FLAG_RECTANGLE ) { shape = rectangle; }
if ( FLAG_ELLIPSE ) { shape = ellipse; }
if ( FLAG_REPLACE ) { type = replace; }
if ( FLAG_ADD ) { type = add; }
if ( FLAG_SUBTRACT ) { type = subtract; }
if ( FLAG_INTERSECT ) { type = intersect; }
// make sure got parameters before this
if (app.documents.length <= 0) // count of documents viewed
{
if ( DialogModes.NO != app.playbackDisplayDialogs ) {
alert(strTextNeedFile); // only put up dialog if permitted
}
app.preferences.rulerUnits = oldPref;
return false; // if no docs, always return
}
if ( app.activeDocument.height > app.activeDocument.width) { // Portrait
var h = app.activeDocument.width;
var w = app.activeDocument.height;
}
else {
var w = app.activeDocument.width;
var h = app.activeDocument.height;
}
if (arInfo.width.value == 0) {
arInfo.width = w;
}
else {
w = arInfo.width;
}
if (arInfo.height.value == 0) {
arInfo.height = h;
}
else {
h = arInfo.height;
}
app.preferences.rulerUnits = oldPref;
f = arInfo.feather;
if ( DialogModes.ALL == app.playbackDisplayDialogs ) {
var d = this.dlgMain;
d.ip = this;
d.pAndB.arinfo.w.e.text = Number(w);
d.pAndB.arinfo.h.e.text = Number(h);
d.pAndB.ftinfo.f.e.text = Number(f);
d.pAndB.opinfo.ctr.value = arInfo.flagCENTER;
d.pAndB.opinfo.bdr.value = arInfo.flagBORDER;
d.pAndB.aainfo.ant.value = arInfo.flagANTIALIAS;
d.pAndB.shinfo.rct.value = arInfo.flagRECTANGLE;
d.pAndB.shinfo.eps.value = arInfo.flagELLIPSE;
d.pAndB.tyinfo.rpl.value = arInfo.flagREPLACE;
d.pAndB.tyinfo.adr.value = arInfo.flagADD;
d.pAndB.tyinfo.sub.value = arInfo.flagSUBTRACT;
d.pAndB.tyinfo.itc.value = arInfo.flagINTERSECT;
}
return true;
}
/* ==================================================================================================================================================
================================================================================================================================================== */
// routine for running the dialog and it's interactions
this.RunDialog = function () {
var d = this.dlgMain;
// in case hit cancel button, don't close
d.pAndB.buttons.cancelBtn.onClick = function() {
var dToCancel = FindDialog( this );
dToCancel.close( false );
}
// nothing for now
d.onShow = function() {
}
// hit OK, do resize
d.pAndB.buttons.okBtn.onClick = function () {
var wText = d.pAndB.arinfo.w.e.text;
var hText = d.pAndB.arinfo.h.e.text;
var fText = d.pAndB.ftinfo.f.e.text;
var w = Number(wText);
var h = Number(hText);
var f = Number(fText);
var FLAG_CENTER = d.pAndB.opinfo.ctr.value;
var FLAG_BORDER = d.pAndB.opinfo.bdr.value;
var FLAG_ANTIALIAS = d.pAndB.aainfo.ant.value;
var FLAG_RECTANGLE = d.pAndB.shinfo.rct.value;
var FLAG_ELLIPSE = d.pAndB.shinfo.eps.value;
var FLAG_REPLACE = d.pAndB.tyinfo.rpl.value;
var FLAG_ADD = d.pAndB.tyinfo.adr.value;
var FLAG_SUBTRACT = d.pAndB.tyinfo.sub.value;
var FLAG_INTERSECT= d.pAndB.tyinfo.itc.value;
arInfo.flagCENTER = FLAG_CENTER;
arInfo.flagBORDER = FLAG_BORDER;
arInfo.flagANTIALIAS = FLAG_ANTIALIAS;
arInfo.flagRECTANGLE = FLAG_RECTANGLE;
arInfo.flagELLIPSE = FLAG_ELLIPSE;
arInfo.flagREPLACE = FLAG_REPLACE;
arInfo.flagADD = FLAG_ADD;
arInfo.flagSUBTRACT = FLAG_SUBTRACT;
arInfo.flagINTERSECT = FLAG_INTERSECT;
var inputErr = false;
// Use Radio Buttons settings
if ( FLAG_RECTANGLE ) { shape = rectangle; }
if ( FLAG_ELLIPSE ) { shape = ellipse; }
if ( FLAG_REPLACE ) { type = replace; }
if ( FLAG_ADD ) { type = add; }
if ( FLAG_SUBTRACT ) { type = subtract; }
if ( FLAG_INTERSECT ) { type = intersect; }
if ( isNaN( w ) || isNaN( h ) ) {
if ( DialogModes.NO != app.playbackDisplayDialogs ) {
alert( strTextInvalidType );
}
if (isNaN( w )) {
arInfo.width = new UnitValue( 1, "px" );
d.pAndB.arinfo.w.e.text = 1;
} else {
arInfo.height = new UnitValue( 1, "px" );
d.pAndB.arinfo.h.e.text = 1;
}
return false;
}
else if ( w <= 0) {
inputErr = true;
arInfo.width = new UnitValue( 1, "px" );
d.pAndB.arinfo.w.e.text = 1;
}
else if ( w > 30000) {
inputErr = true;
arInfo.width = new UnitValue( 30000, "px" );
d.pAndB.arinfo.w.e.text = 30000;
}
else if ( h <= 0) {
inputErr = true;
arInfo.height = new UnitValue( 1, "px" );
d.pAndB.arinfo.h.e.text = 1;
}
else if ( h > 30000) {
inputErr = true;
arInfo.height = new UnitValue( 30000, "px" );
d.pAndB.arinfo.h.e.text = 30000;
}
if (inputErr) {
if ( DialogModes.NO != app.playbackDisplayDialogs ) {
alert( strTextInvalidNum );
}
return false;
}
if ( isNaN( f ) ) {
if ( DialogModes.NO != app.playbackDisplayDialogs ) {
alert( strTextInvalidType );
}
if (isNaN( f )) {
arInfo.width = new UnitValue( 0, "px" );
d.pAndB.ftinfo.f.e.text = 0;
}
return false;
}
else if ( f < 0) {
inputErr = true;
arInfo.width = new UnitValue( 0, "px" );
d.pAndB.ftinfo.f.e.text = 0;
}
else if ( f > 30000) {
inputErr = true;
arInfo.width = new UnitValue( 30000, "px" );
d.pAndB.ftinfo.w.e.text = 30000;
}
arInfo.width = new UnitValue( w, "px" );
arInfo.height = new UnitValue( h, "px" );
arInfo.feather = new UnitValue( f, "px" );
if (inputErr) {
if ( DialogModes.NO != app.playbackDisplayDialogs ) {
alert( strTextInvalidNum );
}
return false;
}
if (showparms) {
alert( "Dialog State" + " " +
"Center " + FLAG_CENTER + " " + arInfo.flagCENTER +
" Border " + FLAG_BORDER + " " + arInfo.flagBORDER +
" Anti_Alias " + FLAG_ANTIALIAS + " " + arInfo.flagANTIALIAS +
" Rectantangle " + FLAG_RECTANGLE + " " + arInfo.flagRECTANGLE +
" Ellipse " + FLAG_ELLIPSE + " " + arInfo.flagELLIPSE +
" Replace " + FLAG_REPLACE + " " + arInfo.flagREPLACE +
" Add " + FLAG_ADD + " " + arInfo.flagADD +
" Substract " + FLAG_SUBTRACT + " " + arInfo.flagSUBTRACT +
" Intersect " + FLAG_INTERSECT + " " + arInfo.flagINTERSECT); }
if (showparms) {alert("From Dialog " + arInfo.width.value + ":" + arInfo.height.value + " Center " + FLAG_CENTER + " Border " + FLAG_BORDER +" Shape " + shape + " Selection Type " + type + " Feather " + arInfo.feather.value + " Anti-Alias " + FLAG_ANTIALIAS ); }
if (ARselect(arInfo.width.value , arInfo.height.value, FLAG_CENTER, FLAG_BORDER, shape, type, arInfo.feather.value, FLAG_ANTIALIAS )) { // the whole point
// error, input
}
d.close(true);
return;
}
if (!this.InitVariables())
{
return true; // handled it
}
// give the hosting app the focus before showing the dialog
app.bringToFront();
this.dlgMain.center();
return d.show();
}
}
/* ==================================================================================================================================================
================================================================================================================================================== */
function CheckVersion() {
var numberArray = version.split(".");
if ( numberArray[0] < 10 ) {
if ( DialogModes.NO != app.playbackDisplayDialogs ) {
alert( strMustUse );
}
throw( strMustUse );
}
}
function FindDialog( inItem ) {
var w = inItem;
while ( 'dialog' != w.type ) {
if ( undefined == w.parent ) {
w = null;
break;
}
w = w.parent;
}
return w;
}
/* Function: objectToDescriptor
// Usage: create an ActionDescriptor from a JavaScript Object
// Input: JavaScript Object (o)
// Pre process converter (f)
// Return: ActionDescriptor
// NOTE: Only boolean, string, and number are supported, use a pre processor
// to convert (f) other types to one of these forms.
//////////////////////////////////////////////////////////////////////////// */
function objectToDescriptor (o, f) {
if (undefined != f) {
o = f(o);
}
var d = new ActionDescriptor;
var l = o.reflect.properties.length;
for (var i = 0; i < l; i++ ) {
var k = o.reflect.properties[i].toString();
if (k == "__proto__" || k == "__count__" || k == "__class__" || k == "reflect")
continue;
var v = o[ k ];
k = app.stringIDToTypeID(k);
switch ( typeof(v) ) {
case "boolean":
d.putBoolean(k, v);
break;
case "string":
d.putString(k, v);
break;
case "number":
d.putDouble(k, v);
break;
default:
{
if ( v instanceof UnitValue ) {
var uc = new Object;
uc["px"] = charIDToTypeID("#Rlt"); // unitDistance
uc["%"] = charIDToTypeID("#Prc"); // unitPercent
d.putUnitDouble(k, uc[v.type], v.value);
} else {
throw( new Error("Unsupported type in objectToDescriptor " + typeof(v) ) );
}
}
}
}
return d;
}
/* Function: descriptorToObject
// Usage: update a JavaScript Object from an ActionDescriptor
// Input: JavaScript Object (o), current object to update (output)
// Photoshop ActionDescriptor (d), descriptor to pull new params for object from
// JavaScript Function (f), post process converter utility to convert
// Return: Nothing, update is applied to passed in JavaScript Object (o)
// NOTE: Only boolean, string, and number are supported, use a post processor
// to convert (f) other types to one of these forms.
/////////////////////////////////////////////////////////////////////////////// */
function descriptorToObject (o, d, f) {
var l = d.count;
for (var i = 0; i < l; i++ ) {
var k = d.getKey(i); // i + 1 ?
var t = d.getType(k);
strk = app.typeIDToStringID(k);
switch (t) {
case DescValueType.BOOLEANTYPE:
o[strk] = d.getBoolean(k);
break;
case DescValueType.STRINGTYPE:
o[strk] = d.getString(k);
break;
case DescValueType.DOUBLETYPE:
o[strk] = d.getDouble(k);
break;
case DescValueType.UNITDOUBLE:
{
var uc = new Object;
uc[charIDToTypeID("#Rlt")] = "px"; // unitDistance
uc[charIDToTypeID("#Prc")] = "%"; // unitPercent
uc[charIDToTypeID("#Pxl")] = "px"; // unitPixels
var ut = d.getUnitDoubleType(k);
var uv = d.getUnitDoubleValue(k);
o[strk] = new UnitValue( uv, uc[ut] );
}
break;
case DescValueType.INTEGERTYPE:
case DescValueType.ALIASTYPE:
case DescValueType.CLASSTYPE:
case DescValueType.ENUMERATEDTYPE:
case DescValueType.LISTTYPE:
case DescValueType.OBJECTTYPE:
case DescValueType.RAWTYPE:
case DescValueType.REFERENCETYPE:
default:
throw( new Error("Unsupported type in descriptorToObject " + t ) );
}
}
if (undefined != f) {
o = f(o);
}
}
/* Function: ARInfo
// Usage: object for holding the dialog parameters
// Input: <none>
// Return: object holding the size info
/////////////////////////////////////////////////////////////////////////////// */
function ARInfo() {
this.height = new UnitValue( 0, "px" );
this.width = new UnitValue( 0, "px" );
this.feather = new UnitValue(0, "px");
this.flagCENTER = FLAG_CENTER;
this.flagBORDER = FLAG_BORDER;
this.flagANTIALIAS = FLAG_ANTIALIAS;
this.flagRECTANGLE = FLAG_RECTANGLE;
this.flagELLIPSE = FLAG_ELLIPSE;
this.flagREPLACE = FLAG_REPLACE;
this.flagADD = FLAG_ADD;
this.flagSUBTRACT = FLAG_SUBTRACT;
this.flagINTERSECT = FLAG_INTERSECT;
}
/* End Aspect Ratio Selection.jsx */
|
|
#20
| ||||
| ||||
| Re: Script to center-crop images to a fixed ratio Thanks jjmacks for the Script. That is very good. An improvement would be still, if it is possible presets to save and load function! Thanks Wolfgang |
|
#21
| |||
| |||
| Re: Script to center-crop images to a fixed ratio Wolfgang As a Photoshop script plug-in you can record its use in and action. The setting you set in the Plug-ins dialog during recording the action is recorded in the action and will be used when you play the action. You can of course turn the dialog on in the action and make that step interactive. You can download this script and many more here http://mouseprints.net/old/dpr/ReadMe.html examples http://www.mouseprints.net/old/dpr/Examples/ |
| Thread Tools | |
| |
| | ||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Not seeing SOME images | mikajomc | Forums Q&A | 4 | 01-23-2008 03:37 PM |
| Script to Detect Upright and View images | Cameraken | Photoshop Scripting | 4 | 01-08-2008 07:50 AM |
| Other festive/xmas Images | palms1 | Photo-Based Art | 13 | 12-19-2007 07:14 AM |
| Protecting images on your website | ChinaMark | Your Website | 4 | 11-16-2007 06:11 PM |
| HDR - ( High Dynamic Range ) Images | CJ Swartz | HDR/HDRi and Tone Mapping | 6 | 11-12-2007 03:40 PM |