Skip to main content
mirza5313
Known Participant
June 29, 2017
Answered

Action that remove background and image batch process

  • June 29, 2017
  • 4 replies
  • 22773 views

Hi, I have a bunch of images just like attached below in terms of size and feel, I just want to make an action to remove background size and gradients effects are same just like examples I have attached here, so there are any possibilities to make such kind of action to auto remove all background?

Thanks in advance

FINAL RESULT that I want

This topic has been closed for replies.
Correct answer c.pfaffenbichler

On CC 2017 this provides halfway decent results for the test files (utilising the four-corner-Magic-Wand-Selection as proposed by JJMack):

// 2017, use it at your own risk;

#target photoshop

if (app.documents.length > 0) {

var myDocument = app.activeDocument;

var originalRulerUnits = app.preferences.rulerUnits;

app.preferences.rulerUnits = Units.PIXELS;

myDocument.selection.deselect();

// magic wand selection;

magicWandTool (10,10);

magicWandTool (myDocument.width-10,10);

magicWandTool (myDocument.width-10,myDocument.height-10);

magicWandTool (10,myDocument.height-10);

// invert selection;

myDocument.selection.invert();

// layer via copy;

var id14 = charIDToTypeID( "CpTL" );

executeAction( id14, undefined, DialogModes.NO );

var thisLayer = myDocument.activeLayer;

// hide others;

hideOthers ();

// remove potential dirt;

loadTransparency(false);

myDocument.selection.contract(10);

myDocument.selection.expand(15);

myDocument.selection.invert();

myDocument.selection.clear();

myDocument.selection.deselect();

// trim with 4px edge;

cropTo(thisLayer.bounds[0]-4, thisLayer.bounds[1]-4, thisLayer.bounds[2]+4, thisLayer.bounds[3]+4);

// reset ruler;

app.preferences.rulerUnits = originalRulerUnits;

};

////// function //////

function magicWandTool (theX, theY) {

// =======================================================

var idslct = charIDToTypeID( "slct" );

    var desc12 = new ActionDescriptor();

    var idnull = charIDToTypeID( "null" );

        var ref5 = new ActionReference();

        var idmagicWandTool = stringIDToTypeID( "magicWandTool" );

        ref5.putClass( idmagicWandTool );

    desc12.putReference( idnull, ref5 );

/*    var iddontRecord = stringIDToTypeID( "dontRecord" );

    desc12.putBoolean( iddontRecord, true );

    var idforceNotify = stringIDToTypeID( "forceNotify" );

    desc12.putBoolean( idforceNotify, true );*/

executeAction( idslct, desc12, DialogModes.NO );

// =======================================================

var idAddT = charIDToTypeID( "AddT" );

    var desc4 = new ActionDescriptor();

    var idnull = charIDToTypeID( "null" );

        var ref2 = new ActionReference();

        var idChnl = charIDToTypeID( "Chnl" );

        var idfsel = charIDToTypeID( "fsel" );

        ref2.putProperty( idChnl, idfsel );

    desc4.putReference( idnull, ref2 );

    var idT = charIDToTypeID( "T   " );

        var desc5 = new ActionDescriptor();

        var idHrzn = charIDToTypeID( "Hrzn" );

        var idPxl = charIDToTypeID( "#Pxl" );

        desc5.putUnitDouble( idHrzn, idPxl, theX );

        var idVrtc = charIDToTypeID( "Vrtc" );

        var idPxl = charIDToTypeID( "#Pxl" );

        desc5.putUnitDouble( idVrtc, idPxl, theY );

    var idPnt = charIDToTypeID( "Pnt " );

    desc4.putObject( idT, idPnt, desc5 );

    var idTlrn = charIDToTypeID( "Tlrn" );

    desc4.putInteger( idTlrn, 36 );

    var idAntA = charIDToTypeID( "AntA" );

    desc4.putBoolean( idAntA, true );

executeAction( idAddT, desc4, DialogModes.NO );/*

// =======================================================

var idsetd = charIDToTypeID( "setd" );

    var desc2 = new ActionDescriptor();

    var idnull = charIDToTypeID( "null" );

        var ref1 = new ActionReference();

        var idChnl = charIDToTypeID( "Chnl" );

        var idfsel = charIDToTypeID( "fsel" );

        ref1.putProperty( idChnl, idfsel );

    desc2.putReference( idnull, ref1 );

    var idT = charIDToTypeID( "T   " );

        var desc3 = new ActionDescriptor();

        var idHrzn = charIDToTypeID( "Hrzn" );

        var idPxl = charIDToTypeID( "#Pxl" );

        desc3.putUnitDouble( idHrzn, idPxl, theX );

        var idVrtc = charIDToTypeID( "Vrtc" );

        var idPxl = charIDToTypeID( "#Pxl" );

        desc3.putUnitDouble( idVrtc, idPxl, theY );

    var idPnt = charIDToTypeID( "Pnt " );

    desc2.putObject( idT, idPnt, desc3 );

    var idTlrn = charIDToTypeID( "Tlrn" );

    desc2.putInteger( idTlrn, 36 );

    var idMrgd = charIDToTypeID( "Mrgd" );

    desc2.putBoolean( idMrgd, true );

    var idAntA = charIDToTypeID( "AntA" );

    desc2.putBoolean( idAntA, true );

executeAction( idsetd, desc2, DialogModes.NO );*/

};

////// hide others //////

function hideOthers () {

// hide others;

// =======================================================

var idShw = charIDToTypeID( "Shw " );

    var desc2 = new ActionDescriptor();

    var idnull = charIDToTypeID( "null" );

        var list1 = new ActionList();

            var ref1 = new ActionReference();

            var idLyr = charIDToTypeID( "Lyr " );

            var idOrdn = charIDToTypeID( "Ordn" );

            var idTrgt = charIDToTypeID( "Trgt" );

            ref1.putEnumerated( idLyr, idOrdn, idTrgt );

        list1.putReference( ref1 );

    desc2.putList( idnull, list1 );

    var idTglO = charIDToTypeID( "TglO" );

    desc2.putBoolean( idTglO, true );

executeAction( idShw, desc2, DialogModes.NO );

};

////// load transparency //////

function loadTransparency (theInvert) {

// =======================================================

var idsetd = charIDToTypeID( "setd" );

    var desc3 = new ActionDescriptor();

    var idnull = charIDToTypeID( "null" );

        var ref2 = new ActionReference();

        var idChnl = charIDToTypeID( "Chnl" );

        var idfsel = charIDToTypeID( "fsel" );

        ref2.putProperty( idChnl, idfsel );

    desc3.putReference( idnull, ref2 );

    var idT = charIDToTypeID( "T   " );

        var ref3 = new ActionReference();

        var idChnl = charIDToTypeID( "Chnl" );

        var idChnl = charIDToTypeID( "Chnl" );

        var idTrsp = charIDToTypeID( "Trsp" );

        ref3.putEnumerated( idChnl, idChnl, idTrsp );

    desc3.putReference( idT, ref3 );

    desc3.putBoolean(charIDToTypeID("Invr"), theInvert);

executeAction( idsetd, desc3, DialogModes.NO );

};

////// crop //////

function cropTo (x1, y1, x2, y2) {

// =======================================================

var idCrop = charIDToTypeID( "Crop" );

    var desc7 = new ActionDescriptor();

    var idT = charIDToTypeID( "T   " );

        var desc8 = new ActionDescriptor();

        var idTop = charIDToTypeID( "Top " );

        var idPxl = charIDToTypeID( "#Pxl" );

        desc8.putUnitDouble( idTop, idPxl, y1 );

        var idLeft = charIDToTypeID( "Left" );

        var idPxl = charIDToTypeID( "#Pxl" );

        desc8.putUnitDouble( idLeft, idPxl, x1);

        var idBtom = charIDToTypeID( "Btom" );

        var idPxl = charIDToTypeID( "#Pxl" );

        desc8.putUnitDouble( idBtom, idPxl, y2 );

        var idRght = charIDToTypeID( "Rght" );

        var idPxl = charIDToTypeID( "#Pxl" );

        desc8.putUnitDouble( idRght, idPxl, x2 );

    var idRctn = charIDToTypeID( "Rctn" );

    desc7.putObject( idT, idRctn, desc8 );

    var idAngl = charIDToTypeID( "Angl" );

    var idAng = charIDToTypeID( "#Ang" );

    desc7.putUnitDouble( idAngl, idAng, 0.000000 );

    var idDlt = charIDToTypeID( "Dlt " );

    desc7.putBoolean( idDlt, false );

    var idcropAspectRatioModeKey = stringIDToTypeID( "cropAspectRatioModeKey" );

    var idcropAspectRatioModeClass = stringIDToTypeID( "cropAspectRatioModeClass" );

    var idpureAspectRatio = stringIDToTypeID( "pureAspectRatio" );

    desc7.putEnumerated( idcropAspectRatioModeKey, idcropAspectRatioModeClass, idpureAspectRatio );

    var idCnsP = charIDToTypeID( "CnsP" );

    desc7.putBoolean( idCnsP, false );

executeAction( idCrop, desc7, DialogModes.NO );

};

4 replies

bluecd
Inspiring
March 24, 2018

Re 1

Disagree. I am not HIJACKING whatsoever but mention an existing thread for better undersyanding of a problem, for programmer's sake!

Re 2: OK, havent noticed that option.

3. What script listener should I use then?

pixxxelschubser
Community Expert
Community Expert
March 24, 2018

bluecd  schrieb

3. What script listener should I use then?

The same.

But the other LOG FILE on your desktop  --> ScriptingListenerJS.log  (and not  ScriptingListenerVB.log)

(Note: I leave this old thread now.)

c.pfaffenbichler
Community Expert
Community Expert
June 30, 2017

By the way: Compliments on posting three fairly different sample-files for illustrating the variance and for testing right away.

Sometimes posters seem tempted to write lots of text instead of posting images that could clarify the issue easily.

mirza5313
mirza5313Author
Known Participant
July 4, 2017

Thank you so much for the script, I am wondering If could you little amend script for me? I have another script that works with batching image processor please see below but this is not working well for background removel.

What is want is with your script could you please add batch image process as my previous script have with some options? currently, script saves image in a folder called Final, I want form new script to save two variations of sizes 500x500px And another folder with 3000x3000px. so there will be two folders

Thank you so much for your precious help.

Here is my old script:

#target photoshop

cTID = function(s) { return app.charIDToTypeID(s); };

sTID = function(s) { return app.stringIDToTypeID(s); };

/*****************************************

* Remove background script

****************************************/

var prefs = new Object();

var box = new Window('dialog', "Remove background from coins by fiverr.com/babloo");

box.panel0 = box.add('panel', undefined, "Select folder to process");

var browseGrp = box.panel0.add('group', undefined);

browseGrp.orientation = 'row';

var folderpathText = browseGrp.add('edittext', undefined, " ");

folderpathText.preferredSize = [300, 20];

box.panel0.orientation = 'column';

box.panel0.alignChildren = 'left';

box.panel0.margins = 10;

box.panel0.browseBtn = browseGrp.add('button', undefined, "Browse", {

    name: 'Browse'

});

box.panel0.browseBtn.onClick = function() {

    selectFolder();

};

box.group = box.add('group', undefined);

box.group.orientation = 'row';

box.group.text1 = box.group.add('statictext', undefined, "Press OK to confirm");

box.group.okBtn = box.group.add('button', undefined, "OK", {

    name: 'ok'

});

box.group.cancelBtn = box.group.add('button', undefined, "Cancel", {

    name: 'cancel'

});

box.center();

box.result = box.show();

function selectFolder() {

    prefs.imageFolder = Folder.selectDialog("Select the folder to process");

    folderpathText.text = decodeURI(prefs.imageFolder);

if(folderpathText.text == "null")

folderpathText.text = "No folder selected";

   

}

if (box.result == 1) {

  

    if (prefs.imageFolder != null) processFolder(prefs.imageFolder);

   

  alert("All files are processed successfully and saved in final folder");

}

function processFolder(folder) {

    var fileList = folder.getFiles(/\.(jpg)$/i);

    var saveFolder = Folder(decodeURI(folder) + "/Final");

    if (!saveFolder.exists)

  saveFolder.create();

   

   

    for (var i = 0; i < fileList.length; i++) {

        var file = fileList;

        if (file instanceof File) {

            var doc = open(file);

            var docName = doc.name;

            docName = docName.match(/(.*)(\.[^\.]+)/) ? docName = docName.match(/(.*)(\.[^\.]+)/) : docName = [docName, docName];

           

            var layer = doc.activeLayer;

            var nLayer = layer.duplicate();

            layer.remove();

            RemoveBG(doc);

            doc.crop(doc.activeLayer.bounds);

            

            var l =  doc.artLayers.add();

            l.isBackgroundLayer = true;

           

            doc.resizeImage(UnitValue(2500,"px"),UnitValue(2500,"px"),null,ResampleMethod.BICUBIC);

                           

            SaveJPG (doc, saveFolder, docName[1],"2500X2500");

             doc.resizeImage(UnitValue(500,"px"),UnitValue(500,"px"),null,ResampleMethod.BICUBIC);

                           

            SaveJPG (doc, saveFolder, docName[1],"500X500");

            

            doc.close(SaveOptions.DONOTSAVECHANGES);

        }

    }

}

function SaveJPG(doc, folder, name,suffix) {

    var saveFile = new File(folder + "/" + name +"_" +suffix+".jpg");

    var saveOptions = new JPEGSaveOptions();

    saveOptions.embedColorProfile = true;

    saveOptions.formatOptions = FormatOptions.STANDARDBASELINE;

    saveOptions.matte = MatteType.NONE;

   

    saveOptions.quality = 8

    doc.saveAs(saveFile, saveOptions, true, Extension.LOWERCASE);

}

function getLayerByName(name){

           

            for(var x = 0; x < app.activeDocument.layers.length; x++){

                        var layer = app.activeDocument.layers;

                       

                        if(layer.name == name){

                                return layer;

                            }

                   

                }

            return null;

    }

function RemoveBG(doc) {

function selectLayer(){

        var layer = getLayerByName ("Layer 0");

        layer.visible = true;

        doc.activeLayer = layer;  

  };

 

 

function magicWand(x,y,t,a,c,s) {

    if(arguments.length < 2) return;// make sure have x,y

    if(undefined == t) var t = 32;// set defaults of optional arguments

    if(undefined == a) var a = true;

    if(undefined == c) var c = false;

     if(undefined == s) var s = false;

    var desc = new ActionDescriptor();

        var ref = new ActionReference();

        ref.putProperty( charIDToTypeID('Chnl'), charIDToTypeID('fsel') );

    desc.putReference( charIDToTypeID('null'), ref );

        var positionDesc = new ActionDescriptor();

        positionDesc.putUnitDouble( charIDToTypeID('Hrzn'), charIDToTypeID('#Rlt'), x );

        positionDesc.putUnitDouble( charIDToTypeID('Vrtc'), charIDToTypeID('#Rlt'), y );

    desc.putObject( charIDToTypeID('T   '), charIDToTypeID('Pnt '), positionDesc );

    desc.putInteger( charIDToTypeID('Tlrn'), t);

    desc.putBoolean( charIDToTypeID('Mrgd'), s );

    if(!c) desc.putBoolean( charIDToTypeID( "Cntg" ), c);

    desc.putBoolean( charIDToTypeID('AntA'), a );

    executeAction( charIDToTypeID('setd'), desc, DialogModes.NO );

};

  function step3() {

     //var sColor =  new SolidColor; 

    //sColor.rgb.hexValue = 'ffffff'; 

    //doc.selection.fill(sColor,);

    executeAction(cTID('Dlt '), undefined, DialogModes.NO);

};

  function step4(enabled, withDialog) {

    app.activeDocument.selection.deselect();

  };

//selectLayer ();

magicWand(170,108,60,true,true,false);

  step3();     

  step4();    

};

c.pfaffenbichler
Community Expert
Community Expert
July 5, 2017

// 2017, use it at your own risk;

#target photoshop

// folder selection;

var theFolder = Folder.selectDialog ("select folder");

if (theFolder) {

var theFiles = theFolder.getFiles(/\.(jpg|tif|eps|psd)$/i)

};

// process the files;

if (theFiles.length > 0) {

var folder1 = theFolder+"/500x500";

var folder2 = theFolder+"/3000x3000";

if (Folder(folder1).exists == false) {Folder(folder1).create()};

if (Folder(folder2).exists == false) {Folder(folder2).create()};

for (var x = 0; x < theFiles.length; x++) {

processFile (theFiles, folder1, folder2)

}

};

////// function //////

function processFile (theFile, folder1, folder2) {

// jpg options; 

var jpegOptions = new JPEGSaveOptions(); 

jpegOptions.quality = 10; 

jpegOptions.embedColorProfile = true; 

jpegOptions.matte = MatteType.NONE; 

// diplicate image;

var theOriginal = app.open(theFile);//app.activeDocument;

var theName = theOriginal.name.match(/(.*)\.[^\.]+$/)[1];

var myDocument = theOriginal.duplicate(theName, true);

app.activeDocument = theOriginal;

theOriginal.close();

// do stuff;

var originalRulerUnits = app.preferences.rulerUnits;

app.preferences.rulerUnits = Units.PIXELS;

myDocument.selection.deselect();

// magic wand selection;

magicWandTool (10,10);

magicWandTool (myDocument.width-10,10);

magicWandTool (myDocument.width-10,myDocument.height-10);

magicWandTool (10,myDocument.height-10);

// invert selection;

myDocument.selection.invert();

// layer via copy;

var id14 = charIDToTypeID( "CpTL" );

executeAction( id14, undefined, DialogModes.NO );

var thisLayer = myDocument.activeLayer;

// hide others;

hideOthers ();

// remove potential dirt;

loadTransparency(false);

myDocument.selection.contract(10);

myDocument.selection.expand(15);

myDocument.selection.invert();

myDocument.selection.clear();

myDocument.selection.deselect();

// trim with 4px edge;

cropTo(thisLayer.bounds[0]-1, thisLayer.bounds[1]-1, thisLayer.bounds[2]+1, thisLayer.bounds[3]+1);

// squaer;

myDocument.resizeCanvas(Math.max(myDocument.width, myDocument.height), Math.max(myDocument.width, myDocument.height), AnchorPosition.MIDDLECENTER);

//

myDocument.resizeImage(3000, 3000, myDocument.resolution, ResampleMethod.BICUBICAUTOMATIC);

myDocument.saveAs(new File(folder2 + "/" + theName + "_3000x3000.jpg"), jpegOptions, true);

myDocument.activeHistoryState = myDocument.historyStates[myDocument.historyStates.length-2];

myDocument.resizeImage(500, 500, myDocument.resolution, ResampleMethod.BICUBICAUTOMATIC);

myDocument.saveAs(new File(folder1 + "/" + theName + "_500x500.jpg"), jpegOptions, true);

// close;

myDocument.close(SaveOptions.DONOTSAVECHANGES);

// reset ruler;

app.preferences.rulerUnits = originalRulerUnits;

};

////// function //////

function magicWandTool (theX, theY) {

// =======================================================

var idslct = charIDToTypeID( "slct" );

    var desc12 = new ActionDescriptor();

    var idnull = charIDToTypeID( "null" );

        var ref5 = new ActionReference();

        var idmagicWandTool = stringIDToTypeID( "magicWandTool" );

        ref5.putClass( idmagicWandTool );

    desc12.putReference( idnull, ref5 );

executeAction( idslct, desc12, DialogModes.NO );

// =======================================================

var idAddT = charIDToTypeID( "AddT" );

    var desc4 = new ActionDescriptor();

    var idnull = charIDToTypeID( "null" );

        var ref2 = new ActionReference();

        var idChnl = charIDToTypeID( "Chnl" );

        var idfsel = charIDToTypeID( "fsel" );

        ref2.putProperty( idChnl, idfsel );

    desc4.putReference( idnull, ref2 );

    var idT = charIDToTypeID( "T   " );

        var desc5 = new ActionDescriptor();

        var idHrzn = charIDToTypeID( "Hrzn" );

        var idPxl = charIDToTypeID( "#Pxl" );

        desc5.putUnitDouble( idHrzn, idPxl, theX );

        var idVrtc = charIDToTypeID( "Vrtc" );

        var idPxl = charIDToTypeID( "#Pxl" );

        desc5.putUnitDouble( idVrtc, idPxl, theY );

    var idPnt = charIDToTypeID( "Pnt " );

    desc4.putObject( idT, idPnt, desc5 );

    var idTlrn = charIDToTypeID( "Tlrn" );

    desc4.putInteger( idTlrn, 36 );

    desc4.putBoolean( charIDToTypeID( "Cntg" ), true );

    var idAntA = charIDToTypeID( "AntA" );

    desc4.putBoolean( idAntA, true );

executeAction( idAddT, desc4, DialogModes.NO );

};

////// hide others //////

function hideOthers () {

// hide others;

// =======================================================

var idShw = charIDToTypeID( "Shw " );

    var desc2 = new ActionDescriptor();

    var idnull = charIDToTypeID( "null" );

        var list1 = new ActionList();

            var ref1 = new ActionReference();

            var idLyr = charIDToTypeID( "Lyr " );

            var idOrdn = charIDToTypeID( "Ordn" );

            var idTrgt = charIDToTypeID( "Trgt" );

            ref1.putEnumerated( idLyr, idOrdn, idTrgt );

        list1.putReference( ref1 );

    desc2.putList( idnull, list1 );

    var idTglO = charIDToTypeID( "TglO" );

    desc2.putBoolean( idTglO, true );

executeAction( idShw, desc2, DialogModes.NO );

};

////// load transparency //////

function loadTransparency (theInvert) {

// =======================================================

var idsetd = charIDToTypeID( "setd" );

    var desc3 = new ActionDescriptor();

    var idnull = charIDToTypeID( "null" );

        var ref2 = new ActionReference();

        var idChnl = charIDToTypeID( "Chnl" );

        var idfsel = charIDToTypeID( "fsel" );

        ref2.putProperty( idChnl, idfsel );

    desc3.putReference( idnull, ref2 );

    var idT = charIDToTypeID( "T   " );

        var ref3 = new ActionReference();

        var idChnl = charIDToTypeID( "Chnl" );

        var idChnl = charIDToTypeID( "Chnl" );

        var idTrsp = charIDToTypeID( "Trsp" );

        ref3.putEnumerated( idChnl, idChnl, idTrsp );

    desc3.putReference( idT, ref3 );

    desc3.putBoolean(charIDToTypeID("Invr"), theInvert);

executeAction( idsetd, desc3, DialogModes.NO );

};

////// crop //////

function cropTo (x1, y1, x2, y2) {

// =======================================================

var idCrop = charIDToTypeID( "Crop" );

    var desc7 = new ActionDescriptor();

    var idT = charIDToTypeID( "T   " );

        var desc8 = new ActionDescriptor();

        var idTop = charIDToTypeID( "Top " );

        var idPxl = charIDToTypeID( "#Pxl" );

        desc8.putUnitDouble( idTop, idPxl, y1 );

        var idLeft = charIDToTypeID( "Left" );

        var idPxl = charIDToTypeID( "#Pxl" );

        desc8.putUnitDouble( idLeft, idPxl, x1);

        var idBtom = charIDToTypeID( "Btom" );

        var idPxl = charIDToTypeID( "#Pxl" );

        desc8.putUnitDouble( idBtom, idPxl, y2 );

        var idRght = charIDToTypeID( "Rght" );

        var idPxl = charIDToTypeID( "#Pxl" );

        desc8.putUnitDouble( idRght, idPxl, x2 );

    var idRctn = charIDToTypeID( "Rctn" );

    desc7.putObject( idT, idRctn, desc8 );

    var idAngl = charIDToTypeID( "Angl" );

    var idAng = charIDToTypeID( "#Ang" );

    desc7.putUnitDouble( idAngl, idAng, 0.000000 );

    var idDlt = charIDToTypeID( "Dlt " );

    desc7.putBoolean( idDlt, false );

    var idcropAspectRatioModeKey = stringIDToTypeID( "cropAspectRatioModeKey" );

    var idcropAspectRatioModeClass = stringIDToTypeID( "cropAspectRatioModeClass" );

    var idpureAspectRatio = stringIDToTypeID( "pureAspectRatio" );

    desc7.putEnumerated( idcropAspectRatioModeKey, idcropAspectRatioModeClass, idpureAspectRatio );

    var idCnsP = charIDToTypeID( "CnsP" );

    desc7.putBoolean( idCnsP, false );

executeAction( idCrop, desc7, DialogModes.NO );

};

////// trim //////

function trimTransparent () {

// =======================================================

var idtrim = stringIDToTypeID( "trim" );

    var desc11 = new ActionDescriptor();

    var idtrimBasedOn = stringIDToTypeID( "trimBasedOn" );

    var idtrimBasedOn = stringIDToTypeID( "trimBasedOn" );

    var idTrns = charIDToTypeID( "Trns" );

    desc11.putEnumerated( idtrimBasedOn, idtrimBasedOn, idTrns );

    var idTop = charIDToTypeID( "Top " );

    desc11.putBoolean( idTop, true );

    var idBtom = charIDToTypeID( "Btom" );

    desc11.putBoolean( idBtom, true );

    var idLeft = charIDToTypeID( "Left" );

    desc11.putBoolean( idLeft, true );

    var idRght = charIDToTypeID( "Rght" );

    desc11.putBoolean( idRght, true );

executeAction( idtrim, desc11, DialogModes.NO );

};

c.pfaffenbichler
Community Expert
c.pfaffenbichlerCommunity ExpertCorrect answer
Community Expert
June 30, 2017

On CC 2017 this provides halfway decent results for the test files (utilising the four-corner-Magic-Wand-Selection as proposed by JJMack):

// 2017, use it at your own risk;

#target photoshop

if (app.documents.length > 0) {

var myDocument = app.activeDocument;

var originalRulerUnits = app.preferences.rulerUnits;

app.preferences.rulerUnits = Units.PIXELS;

myDocument.selection.deselect();

// magic wand selection;

magicWandTool (10,10);

magicWandTool (myDocument.width-10,10);

magicWandTool (myDocument.width-10,myDocument.height-10);

magicWandTool (10,myDocument.height-10);

// invert selection;

myDocument.selection.invert();

// layer via copy;

var id14 = charIDToTypeID( "CpTL" );

executeAction( id14, undefined, DialogModes.NO );

var thisLayer = myDocument.activeLayer;

// hide others;

hideOthers ();

// remove potential dirt;

loadTransparency(false);

myDocument.selection.contract(10);

myDocument.selection.expand(15);

myDocument.selection.invert();

myDocument.selection.clear();

myDocument.selection.deselect();

// trim with 4px edge;

cropTo(thisLayer.bounds[0]-4, thisLayer.bounds[1]-4, thisLayer.bounds[2]+4, thisLayer.bounds[3]+4);

// reset ruler;

app.preferences.rulerUnits = originalRulerUnits;

};

////// function //////

function magicWandTool (theX, theY) {

// =======================================================

var idslct = charIDToTypeID( "slct" );

    var desc12 = new ActionDescriptor();

    var idnull = charIDToTypeID( "null" );

        var ref5 = new ActionReference();

        var idmagicWandTool = stringIDToTypeID( "magicWandTool" );

        ref5.putClass( idmagicWandTool );

    desc12.putReference( idnull, ref5 );

/*    var iddontRecord = stringIDToTypeID( "dontRecord" );

    desc12.putBoolean( iddontRecord, true );

    var idforceNotify = stringIDToTypeID( "forceNotify" );

    desc12.putBoolean( idforceNotify, true );*/

executeAction( idslct, desc12, DialogModes.NO );

// =======================================================

var idAddT = charIDToTypeID( "AddT" );

    var desc4 = new ActionDescriptor();

    var idnull = charIDToTypeID( "null" );

        var ref2 = new ActionReference();

        var idChnl = charIDToTypeID( "Chnl" );

        var idfsel = charIDToTypeID( "fsel" );

        ref2.putProperty( idChnl, idfsel );

    desc4.putReference( idnull, ref2 );

    var idT = charIDToTypeID( "T   " );

        var desc5 = new ActionDescriptor();

        var idHrzn = charIDToTypeID( "Hrzn" );

        var idPxl = charIDToTypeID( "#Pxl" );

        desc5.putUnitDouble( idHrzn, idPxl, theX );

        var idVrtc = charIDToTypeID( "Vrtc" );

        var idPxl = charIDToTypeID( "#Pxl" );

        desc5.putUnitDouble( idVrtc, idPxl, theY );

    var idPnt = charIDToTypeID( "Pnt " );

    desc4.putObject( idT, idPnt, desc5 );

    var idTlrn = charIDToTypeID( "Tlrn" );

    desc4.putInteger( idTlrn, 36 );

    var idAntA = charIDToTypeID( "AntA" );

    desc4.putBoolean( idAntA, true );

executeAction( idAddT, desc4, DialogModes.NO );/*

// =======================================================

var idsetd = charIDToTypeID( "setd" );

    var desc2 = new ActionDescriptor();

    var idnull = charIDToTypeID( "null" );

        var ref1 = new ActionReference();

        var idChnl = charIDToTypeID( "Chnl" );

        var idfsel = charIDToTypeID( "fsel" );

        ref1.putProperty( idChnl, idfsel );

    desc2.putReference( idnull, ref1 );

    var idT = charIDToTypeID( "T   " );

        var desc3 = new ActionDescriptor();

        var idHrzn = charIDToTypeID( "Hrzn" );

        var idPxl = charIDToTypeID( "#Pxl" );

        desc3.putUnitDouble( idHrzn, idPxl, theX );

        var idVrtc = charIDToTypeID( "Vrtc" );

        var idPxl = charIDToTypeID( "#Pxl" );

        desc3.putUnitDouble( idVrtc, idPxl, theY );

    var idPnt = charIDToTypeID( "Pnt " );

    desc2.putObject( idT, idPnt, desc3 );

    var idTlrn = charIDToTypeID( "Tlrn" );

    desc2.putInteger( idTlrn, 36 );

    var idMrgd = charIDToTypeID( "Mrgd" );

    desc2.putBoolean( idMrgd, true );

    var idAntA = charIDToTypeID( "AntA" );

    desc2.putBoolean( idAntA, true );

executeAction( idsetd, desc2, DialogModes.NO );*/

};

////// hide others //////

function hideOthers () {

// hide others;

// =======================================================

var idShw = charIDToTypeID( "Shw " );

    var desc2 = new ActionDescriptor();

    var idnull = charIDToTypeID( "null" );

        var list1 = new ActionList();

            var ref1 = new ActionReference();

            var idLyr = charIDToTypeID( "Lyr " );

            var idOrdn = charIDToTypeID( "Ordn" );

            var idTrgt = charIDToTypeID( "Trgt" );

            ref1.putEnumerated( idLyr, idOrdn, idTrgt );

        list1.putReference( ref1 );

    desc2.putList( idnull, list1 );

    var idTglO = charIDToTypeID( "TglO" );

    desc2.putBoolean( idTglO, true );

executeAction( idShw, desc2, DialogModes.NO );

};

////// load transparency //////

function loadTransparency (theInvert) {

// =======================================================

var idsetd = charIDToTypeID( "setd" );

    var desc3 = new ActionDescriptor();

    var idnull = charIDToTypeID( "null" );

        var ref2 = new ActionReference();

        var idChnl = charIDToTypeID( "Chnl" );

        var idfsel = charIDToTypeID( "fsel" );

        ref2.putProperty( idChnl, idfsel );

    desc3.putReference( idnull, ref2 );

    var idT = charIDToTypeID( "T   " );

        var ref3 = new ActionReference();

        var idChnl = charIDToTypeID( "Chnl" );

        var idChnl = charIDToTypeID( "Chnl" );

        var idTrsp = charIDToTypeID( "Trsp" );

        ref3.putEnumerated( idChnl, idChnl, idTrsp );

    desc3.putReference( idT, ref3 );

    desc3.putBoolean(charIDToTypeID("Invr"), theInvert);

executeAction( idsetd, desc3, DialogModes.NO );

};

////// crop //////

function cropTo (x1, y1, x2, y2) {

// =======================================================

var idCrop = charIDToTypeID( "Crop" );

    var desc7 = new ActionDescriptor();

    var idT = charIDToTypeID( "T   " );

        var desc8 = new ActionDescriptor();

        var idTop = charIDToTypeID( "Top " );

        var idPxl = charIDToTypeID( "#Pxl" );

        desc8.putUnitDouble( idTop, idPxl, y1 );

        var idLeft = charIDToTypeID( "Left" );

        var idPxl = charIDToTypeID( "#Pxl" );

        desc8.putUnitDouble( idLeft, idPxl, x1);

        var idBtom = charIDToTypeID( "Btom" );

        var idPxl = charIDToTypeID( "#Pxl" );

        desc8.putUnitDouble( idBtom, idPxl, y2 );

        var idRght = charIDToTypeID( "Rght" );

        var idPxl = charIDToTypeID( "#Pxl" );

        desc8.putUnitDouble( idRght, idPxl, x2 );

    var idRctn = charIDToTypeID( "Rctn" );

    desc7.putObject( idT, idRctn, desc8 );

    var idAngl = charIDToTypeID( "Angl" );

    var idAng = charIDToTypeID( "#Ang" );

    desc7.putUnitDouble( idAngl, idAng, 0.000000 );

    var idDlt = charIDToTypeID( "Dlt " );

    desc7.putBoolean( idDlt, false );

    var idcropAspectRatioModeKey = stringIDToTypeID( "cropAspectRatioModeKey" );

    var idcropAspectRatioModeClass = stringIDToTypeID( "cropAspectRatioModeClass" );

    var idpureAspectRatio = stringIDToTypeID( "pureAspectRatio" );

    desc7.putEnumerated( idcropAspectRatioModeKey, idcropAspectRatioModeClass, idpureAspectRatio );

    var idCnsP = charIDToTypeID( "CnsP" );

    desc7.putBoolean( idCnsP, false );

executeAction( idCrop, desc7, DialogModes.NO );

};

JJMack
Community Expert
Community Expert
June 29, 2017

You do not start what size and resolution your images are. If the vary all over the place dealing with size can be difficult in actions. Also if you files may be layered documents actions can not loop through the document layers  and remover backgrounds from all raster layers.

An action could process all the image files you want to batch by first flattening document open in  a batch to make have just a background layer.  Convert the background layers to a normal layer.   Use the Magic want tool in contiguous mode sampling the four corners to try to select the type of backgrounds you show in your examples. Or Stroke the edges with the quick selection tool. Clear that selection and trim the transparency created to tightly crop to the object bounds.  Then increase the canvas size so when you save a jpeg there white space on four size.  The main problem is the action does not know  the images resolution so it has no way to know the number of pixels it should increase the canvas size by for that white space you seem to want.  You would override the Actions save as Jpeg on you desktop to save the output  jpeg where you want them.

Download this stroke quick selection tool it adds 150 px on sides 1/2" at 300DPI TrimAndAdd.atn

Crafting Actions Package UPDATED Aug 10, 2014 Added Conditional Action steps to Action Palette Tips.
Contains

Example
Download

JJMack
JJMack
Community Expert
Community Expert
June 29, 2017

I use CC 2014 it seems like the are bugs in CC 2015.5  and CC 2017 when you try to stroke a path with the quick selection tool in an Action those Photoshop versions display an "Program Error"  pop up message.   When I manually try to stroke a path with the quick selection tool CC 2015.5 pop up the Program error window  CC 2017 on the other hand when I try to stroke a path Photoshop Crashes.

There is a Problem trying to use the Magic wand instead  The selection set were not very good compared the Stroking with the Quick selection tool in CC 2014 here is what I see in CC 2014

JJMack