RetouchPRO

Go Back   RetouchPRO > Tools > Software > Photoshop Scripting
Register Blogs FAQ Site Nav Search Today's Posts Mark Forums Read


Photoshop Scripting Learning and sharing for all platforms

Script to center-crop images to a fixed ratio

Reply
 
Thread Tools
  #11  
Old 10-25-2008, 01:46 PM
momono momono is offline
Junior Member
 
Join Date: Oct 2008
Posts: 5
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
Reply With Quote top
  #12  
Old 10-25-2008, 03:01 PM
Juergen D's Avatar
Juergen D Juergen D is offline
Senior Member
 
Join Date: Oct 2006
Location: SW Florida
Posts: 223
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
Reply With Quote top
  #13  
Old 10-25-2008, 05:07 PM
0lBaldy's Avatar
0lBaldy 0lBaldy is offline
Senior Member
Patron
 
Join Date: Oct 2007
Posts: 3,580
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?
Reply With Quote top
  #14  
Old 10-25-2008, 05:19 PM
Juergen D's Avatar
Juergen D Juergen D is offline
Senior Member
 
Join Date: Oct 2006
Location: SW Florida
Posts: 223
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
Reply With Quote top
  #15  
Old 10-26-2008, 02:41 PM
momono momono is offline
Junior Member
 
Join Date: Oct 2008
Posts: 5
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.
Reply With Quote top
  #16  
Old 11-12-2008, 10:05 AM
RetouchJones RetouchJones is offline
Junior Member
 
Join Date: Nov 2008
Posts: 7
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?
Reply With Quote top
  #17  
Old 11-12-2008, 01:38 PM
momono momono is offline
Junior Member
 
Join Date: Oct 2008
Posts: 5
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..
Reply With Quote top
  #18  
Old 11-12-2008, 01:47 PM
RetouchJones RetouchJones is offline
Junior Member
 
Join Date: Nov 2008
Posts: 7
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?
Reply With Quote top
  #19  
Old 11-30-2008, 01:17 PM
jjmacks jjmacks is offline
Junior Member
 
Join Date: Jun 2006
Location: NY
Posts: 5
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  */
Reply With Quote top
  #20  
Old 12-30-2008, 07:14 AM
Gewuerz's Avatar
Gewuerz Gewuerz is offline
Junior Member
 
Join Date: Apr 2006
Location: Germany
Posts: 16
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
Reply With Quote top
Reply

  RetouchPRO > Tools > Software > Photoshop Scripting


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Not seeing SOME images mikajomc Forums Q&A 4 01-23-2008 04:37 PM
Script to Detect Upright and View images Cameraken Photoshop Scripting 4 01-08-2008 08:50 AM
Other festive/xmas Images palms Photo-Based Art 13 12-19-2007 08:14 AM
Protecting images on your website ChinaMark Your Website 4 11-16-2007 07:11 PM
HDR - ( High Dynamic Range ) Images CJ Swartz HDR, Panoramas and Tone Mapping 6 11-12-2007 04:40 PM


All times are GMT -6. The time now is 11:08 AM.


Powered by vBulletin® Version 3.8.4
Copyright ©2000 - 2017, Jelsoft Enterprises Ltd.
SEO by vBSEO ©2011, Crawlability, Inc.
Copyright © 2016 Doug Nelson. All Rights Reserved