├── Paste or Place Inside Selection.jsx ├── README.md └── readme-images ├── active-layer-method.gif ├── paste-or-place-inside-selection-dialog.png └── selection-method.gif /Paste or Place Inside Selection.jsx: -------------------------------------------------------------------------------- 1 | // Paste or Place Inside Selection.jsx 2 | // Version: 0.7. 3 | // https://github.com/joonaspaakko/paste-or-place-inside-selection-photoshop-script 4 | 5 | // Changelog: 6 | 7 | // ********* V.0.6. ********* 8 | // - Tested in PS CC 2019 (20.0.4) 9 | // - Fixed an issue where you would get an error when trying to place image using the active layer method sometimes 10 | // - Updated gifs... 11 | 12 | // ********* V.0.6. ********* 13 | // - Tested in PS CC 2019 (20.0.4) 14 | // - Fixed an issue with anti-aliasing. 15 | // - Fixed an issue with the clipping mask detection where sometimes you'd end up with with an extra empty layer when placing images. 16 | // - Improved the handling SVG (vector): 17 | // 1. Vector images are no longer rasterized. Works with both pasted and placed vector images. 18 | // 2. "Prevent upsizing" option is ignored if the image is vector. Works with both pasted and placed vector images. 19 | // 3. Background is trimmed from placed SVG images. Well not really, but the transparent whitespace is ignored when resizing and aligning. 20 | 21 | // ********* V.0.5. ********* 22 | // - Tested in PS CC 2020 (21.0.2) 23 | // - Fixed and issue that would cause the layer name suffix percentage to be a little off when placing images. Forgot to initiate some code in the last release. 24 | // - Made a small change where the layer name suffix percentage doesn't get the tilde: ~ character if the image size doesn't change. 25 | 26 | // ********* V.0.4. ********* 27 | // - Tested in PS CC 2020 (21.0.2) 28 | // - I fixed an issue where the script would sometimes fail to resize properly 29 | // - Added a new feature that shows the current layer size in percentages by appending it to the layer name. 30 | // - The variable that controls this is called "changeLayerName" 31 | // - Default value: "always" 32 | // - Optional values: 'upsize prevented', 'never' 33 | 34 | // ********* V.0.3. ********* 35 | // - Tested in PS CC 2019 (20.0.4) 36 | // - Added a new option: "Don't upsize past original size" 37 | // - Now works in all of the _possible_ color modes. I realized that 38 | // this script could only be used in RGB color mode due to the way I 39 | // deselected temp channel by activating red + green + blue channels. 40 | // - Fixed a thing where you got a "Paste failed" alert when canceling the open dialog. 41 | // - Change: Only fill will add extra 2px in to the target 42 | // size. It's to account for anti-aliasing / bleedthrough. 43 | // I think it doesn't matter as much when fitting. 44 | // - Change: You no longer need to make a selection before pasting or placing 45 | // image on top of it. It's automatically changed into a normal layer. 46 | 47 | // ********* V.0.2. ********* 48 | // - Tested in PS CC 2019 49 | // - Renewed dialog. Numbers from 1 to 4 can be used as shortcuts. 50 | // - Spacebar used to trigger paste and enter used to trigger place, but now it's reversed. 51 | // - Name changed from "Place Inside Selection.jsx" to "Paste or Place Inside Selection.jsx" 52 | 53 | // ********* V.0.1. ********* 54 | // - First version 55 | // - Written for PS CC 2018 56 | // - Images are placed as Smart Objects and resized to the size of your selection. 57 | // - Does not respect the original size of your image in the sense 58 | // that if you place your image into a selection that is bigger than 59 | // the image, it will ruthlessly upsize it the size of the selection. 60 | 61 | // OPTION! 62 | var changeLayerName = 'always' // values: 'always', 'upsize prevented', 'never' 63 | 64 | // Global variables... 65 | var method = null; 66 | var fit_or_fill = null; 67 | var noUpsize = false; 68 | var clipboardEmpty = false; 69 | var hasSelection = selectionExists(); 70 | var tempChannelName = 'Temp Channel - 0123456789'; 71 | var clipTempLayer = null; 72 | var isVector = false; 73 | var activeLayerVisible = app.activeDocument.activeLayer.visible; 74 | 75 | // Writes one history state.... 76 | app.activeDocument.suspendHistory("Paste or Place Inside Selection.jsx", "init()"); 77 | 78 | function init() { 79 | 80 | // Place options 81 | dialog(); 82 | 83 | // Don't continue if user cancelled using ESC 84 | if ( method != null ) { 85 | 86 | var imageSrc; 87 | 88 | // If PLACE was the chosen method, open up "browse" dialog to find a file to place. 89 | if ( method === 'place' ) { 90 | imageSrc = File.openDialog( 'Open input image...' ); 91 | } 92 | // If PASTE was the chosen method, test clipboard... 93 | else { 94 | imageSrc = "clipboard"; 95 | clipboardEmpty = testClipboard(); 96 | } 97 | 98 | // Don't continue if user cancels the "browse" dialog or if the clipboard is empty 99 | if ( 100 | (imageSrc == "clipboard" && !clipboardEmpty) || 101 | (imageSrc != undefined && imageSrc != null && imageSrc != "clipboard") 102 | ) { 103 | main( imageSrc ); 104 | } 105 | 106 | if ( clipboardEmpty ) { 107 | alert( 'Paste failed \nMake sure you have an image in your clipboard and try again...' ); 108 | } 109 | 110 | } 111 | 112 | } // init(); 113 | 114 | function main( imageSrc ) { 115 | 116 | var doc = app.activeDocument, 117 | activeLayer = doc.activeLayer, 118 | rulerUnits = app.preferences.rulerUnits; 119 | 120 | app.preferences.rulerUnits = Units.PIXELS; 121 | 122 | if ( !hasSelection ) { 123 | // Turn background layer into a normal layer 124 | if ( doc.activeLayer.isBackgroundLayer ) { doc.activeLayer.isBackgroundLayer = false; } 125 | } 126 | 127 | // Could be a layer or a selection 128 | var target = getTargetBounds( doc, activeLayer ); 129 | 130 | if ( hasSelection ) { 131 | saveSelection( doc ); 132 | } 133 | 134 | if ( imageSrc === "clipboard" ) { 135 | pasteIMG( doc, activeLayer, imageSrc, target.width, target.height ); 136 | } 137 | else { 138 | placeIMG( doc, activeLayer, imageSrc, target.width, target.height ); 139 | if ( clipTempLayer ) try { clipTempLayer.name; clipTempLayer.remove(); } catch(e) {} 140 | } 141 | 142 | resizeIMG( doc.activeLayer, target.width, target.height, imageSrc ); 143 | // align( [layerToAlign], [targetBounds] ); 144 | align( doc.activeLayer, target.bounds ); 145 | 146 | // Wrap it up.... 147 | // When there is a selection, we add a Layer Mask to the image. 148 | if ( hasSelection ) { 149 | 150 | loadSelection( doc ); 151 | 152 | // Add Layers Mask 153 | // ======================================================= 154 | var idMk = charIDToTypeID( "Mk " ); 155 | var desc437 = new ActionDescriptor(); 156 | var idNw = charIDToTypeID( "Nw " ); 157 | var idChnl = charIDToTypeID( "Chnl" ); 158 | desc437.putClass( idNw, idChnl ); 159 | var idAt = charIDToTypeID( "At " ); 160 | var ref249 = new ActionReference(); 161 | var idChnl = charIDToTypeID( "Chnl" ); 162 | var idChnl = charIDToTypeID( "Chnl" ); 163 | var idMsk = charIDToTypeID( "Msk " ); 164 | ref249.putEnumerated( idChnl, idChnl, idMsk ); 165 | desc437.putReference( idAt, ref249 ); 166 | var idUsng = charIDToTypeID( "Usng" ); 167 | var idUsrM = charIDToTypeID( "UsrM" ); 168 | var idRvlS = charIDToTypeID( "RvlS" ); 169 | desc437.putEnumerated( idUsng, idUsrM, idRvlS ); 170 | executeAction( idMk, desc437, DialogModes.NO ); 171 | 172 | } 173 | // When there is no selection, a clipping mask is used and both layers are selected. 174 | else { 175 | 176 | // A new clippingmask is created: 177 | if ( !doc.activeLayer.grouped ) doc.activeLayer.grouped = true; 178 | 179 | } 180 | 181 | // Select default channels 182 | var prevActive = doc.activeLayer; 183 | var tempLayer = doc.artLayers.add(); tempLayer.remove(); 184 | doc.activeLayer = prevActive; 185 | 186 | // Reset ruler units 187 | app.preferences.rulerUnits = rulerUnits; 188 | activeLayer.visible = activeLayerVisible; 189 | 190 | } // main(); 191 | 192 | function loadSelection( doc ) { 193 | doc.selection.load( doc.channels[ tempChannelName ], SelectionType.REPLACE ); 194 | doc.channels[ tempChannelName ].remove(); 195 | } 196 | 197 | function saveSelection( doc ) { 198 | var channels = doc.channels; 199 | var tempChannel = channels.add(); 200 | tempChannel.kind = ChannelType.SELECTEDAREA; 201 | tempChannel.name = tempChannelName; 202 | doc.selection.store( channels[ tempChannelName ], SelectionType.REPLACE ); 203 | // Select default channels 204 | var prevActive = doc.activeLayer; 205 | var tempLayer = doc.artLayers.add(); tempLayer.remove(); 206 | doc.activeLayer = prevActive; 207 | } 208 | 209 | function testClipboard() { 210 | 211 | var cEmpty = false, 212 | tempDoc = app.documents.add(); 213 | 214 | try { 215 | 216 | // Paste 217 | // ======================================================= 218 | var idpast = charIDToTypeID( "past" ); 219 | var desc1408 = new ActionDescriptor(); 220 | var idAntA = charIDToTypeID( "AntA" ); 221 | var idAnnt = charIDToTypeID( "Annt" ); 222 | var idAnno = charIDToTypeID( "Anno" ); 223 | desc1408.putEnumerated( idAntA, idAnnt, idAnno ); 224 | var idAs = charIDToTypeID( "As " ); 225 | var idPxel = charIDToTypeID( "Pxel" ); 226 | desc1408.putClass( idAs, idPxel ); 227 | executeAction( idpast, desc1408, DialogModes.NO ); 228 | 229 | } catch(e) { cEmpty = true; } 230 | 231 | tempDoc.close( SaveOptions.DONOTSAVECHANGES ); 232 | 233 | return cEmpty; 234 | 235 | } 236 | 237 | function pasteIMG( doc, activeLayer, imageSrc ) { 238 | 239 | // Paste 240 | // ======================================================= 241 | var idpast = charIDToTypeID( "past" ); 242 | var desc273 = new ActionDescriptor(); 243 | var idAntA = charIDToTypeID( "AntA" ); 244 | desc273.putBoolean( idAntA, true ); 245 | var idAs = charIDToTypeID( "As " ); 246 | var idsmartObject = stringIDToTypeID( "smartObject" ); 247 | desc273.putClass( idAs, idsmartObject ); 248 | var idpushToDesignLibraries = stringIDToTypeID( "pushToDesignLibraries" ); 249 | desc273.putBoolean( idpushToDesignLibraries, false ); 250 | var idFTcs = charIDToTypeID( "FTcs" ); 251 | var idQCSt = charIDToTypeID( "QCSt" ); 252 | var idQcsa = charIDToTypeID( "Qcsa" ); 253 | desc273.putEnumerated( idFTcs, idQCSt, idQcsa ); 254 | var idOfst = charIDToTypeID( "Ofst" ); 255 | var desc274 = new ActionDescriptor(); 256 | var idHrzn = charIDToTypeID( "Hrzn" ); 257 | var idPxl = charIDToTypeID( "#Pxl" ); 258 | desc274.putUnitDouble( idHrzn, idPxl, 0.000000 ); 259 | var idVrtc = charIDToTypeID( "Vrtc" ); 260 | var idPxl = charIDToTypeID( "#Pxl" ); 261 | desc274.putUnitDouble( idVrtc, idPxl, 0.000000 ); 262 | var idOfst = charIDToTypeID( "Ofst" ); 263 | desc273.putObject( idOfst, idOfst, desc274 ); 264 | executeAction( idpast, desc273, DialogModes.NO ); 265 | 266 | if ( doc.activeLayer.kind !== LayerKind.SMARTOBJECT ) { 267 | // Convert pasted image into a Smart Object 268 | var idnewPlacedLayer = stringIDToTypeID( "newPlacedLayer" ); 269 | executeAction( idnewPlacedLayer, undefined, DialogModes.NO ); 270 | } 271 | else { 272 | isVector = true; 273 | } 274 | 275 | doc.activeLayer.name = "[Pasted Image]"; 276 | 277 | } 278 | 279 | function placeIMG( doc, activeLayer, imageSrc ) { 280 | 281 | // Makes sure the placed image size is not constrained by the document. 282 | var resizeImageOnPlaceSetting = getOptionResizeImageDuringPlace(); 283 | resizeImageDuringPlace(false); 284 | 285 | // Place 286 | // ======================================================= 287 | var idPlc = charIDToTypeID( "Plc " ); 288 | var desc394 = new ActionDescriptor(); 289 | var idIdnt = charIDToTypeID( "Idnt" ); 290 | desc394.putInteger( idIdnt, 48 ); 291 | var idnull = charIDToTypeID( "null" ); 292 | desc394.putPath( idnull, new File( imageSrc ) ); 293 | var idFTcs = charIDToTypeID( "FTcs" ); 294 | var idQCSt = charIDToTypeID( "QCSt" ); 295 | var idQcsa = charIDToTypeID( "Qcsa" ); 296 | desc394.putEnumerated( idFTcs, idQCSt, idQcsa ); 297 | var idOfst = charIDToTypeID( "Ofst" ); 298 | var desc395 = new ActionDescriptor(); 299 | var idHrzn = charIDToTypeID( "Hrzn" ); 300 | var idPxl = charIDToTypeID( "#Pxl" ); 301 | desc395.putUnitDouble( idHrzn, idPxl, 0.000000 ); 302 | var idVrtc = charIDToTypeID( "Vrtc" ); 303 | var idPxl = charIDToTypeID( "#Pxl" ); 304 | desc395.putUnitDouble( idVrtc, idPxl, 0.000000 ); 305 | var idOfst = charIDToTypeID( "Ofst" ); 306 | desc394.putObject( idOfst, idOfst, desc395 ); 307 | var idAntA = charIDToTypeID( "AntA" ); 308 | desc394.putBoolean( idAntA, true ); 309 | executeAction( idPlc, desc394, DialogModes.NO ); 310 | 311 | resizeImageDuringPlace( resizeImageOnPlaceSetting ); 312 | 313 | } 314 | 315 | // Preferences > General (Cmd+K) > [ ] Resize Image During Plage 316 | function resizeImageDuringPlace( optParam ) { 317 | var descPreferences = new ActionDescriptor(); 318 | var ref = new ActionReference(); 319 | ref.putProperty( charIDToTypeID('Prpr'), charIDToTypeID('GnrP') ); 320 | ref.putEnumerated( charIDToTypeID('capp'), charIDToTypeID('Ordn'), charIDToTypeID('Trgt') ); 321 | descPreferences.putReference( charIDToTypeID('null'), ref ); 322 | var descSetting = new ActionDescriptor(); 323 | descSetting.putBoolean( stringIDToTypeID('resizePastePlace'), optParam ); 324 | descPreferences.putObject( charIDToTypeID('T '), charIDToTypeID('GnrP'), descSetting ); 325 | executeAction( charIDToTypeID('setd'), descPreferences, DialogModes.NO ); 326 | } 327 | 328 | // Preferences > General (Cmd+K) > [ ] Resize Image During Plage 329 | function getOptionResizeImageDuringPlace() { 330 | var ref = new ActionReference(); 331 | ref.putEnumerated( charIDToTypeID("capp"), charIDToTypeID("Ordn"), charIDToTypeID("Trgt") ); 332 | var desc = executeActionGet(ref).getObjectValue( stringIDToTypeID('generalPreferences') ); 333 | return desc.getBoolean( stringIDToTypeID('resizePastePlace') ) == 0 ? false : true; 334 | } 335 | 336 | function resizeIMG( imageLayer, target_width, target_height, imageSrc ) { 337 | 338 | // Small padding to help with anti-aliasing 339 | target_width = target_width + ( fit_or_fill === 'fill' ? 2 : 0 ); 340 | target_height = target_height + ( fit_or_fill === 'fill' ? 2 : 0 ); 341 | var targetSize = [ target_width, target_height ]; 342 | 343 | var bounds = imageLayer.boundsNoEffects; 344 | var image_width = bounds[2].value - bounds[0].value; 345 | var image_height = bounds[3].value - bounds[1].value; 346 | 347 | // This section normalizes placed images with a different resolution 348 | if ( imageSrc !== "clipboard" ) { 349 | 350 | var dispDialogs = app.displayDialogs; 351 | app.displayDialogs = DialogModes.NO; 352 | 353 | var documentIdBefore = app.activeDocument.id; 354 | var documentsLengthBefore = app.documents.length; 355 | // Open the document separately 356 | // ======================================================= 357 | var idOpn = charIDToTypeID( "Opn " ); 358 | var desc379 = new ActionDescriptor(); 359 | var iddontRecord = stringIDToTypeID( "dontRecord" ); 360 | desc379.putBoolean( iddontRecord, false ); 361 | var idforceNotify = stringIDToTypeID( "forceNotify" ); 362 | desc379.putBoolean( idforceNotify, false ); 363 | var idnull = charIDToTypeID( "null" ); 364 | desc379.putPath( idnull, new File( imageSrc ) ); 365 | var idDocI = charIDToTypeID( "DocI" ); 366 | desc379.putInteger( idDocI, 430 ); 367 | executeAction( idOpn, desc379, DialogModes.NO ); 368 | 369 | var tempDoc = app.activeDocument; 370 | if ( imageSrc.fullName.split('.').pop() === 'svg' ) { 371 | tempDoc.trim( TrimType.TRANSPARENT ); 372 | isVector = true; 373 | } 374 | 375 | var tempDocSize = [ tempDoc.width.as('px'), tempDoc.height.as('px')]; 376 | 377 | 378 | var documentIdAfter = app.activeDocument.id; 379 | var documentsLengthAfter = app.documents.length; 380 | var fileAlreadyOpen = documentsLengthBefore === documentsLengthAfter; 381 | 382 | if ( fileAlreadyOpen ) { 383 | activateDocumentByID( documentIdBefore ); 384 | } 385 | else { 386 | app.activeDocument.close( SaveOptions.DONOTSAVECHANGES ); 387 | } 388 | 389 | app.displayDialogs = dispDialogs; 390 | 391 | var bounds = app.activeDocument.activeLayer.boundsNoEffects; 392 | var placedWidth = bounds[2].value - bounds[0].value; 393 | var placedHeight = bounds[3].value - bounds[1].value; 394 | 395 | var eqSize = calculateNewSize( [placedWidth, placedHeight], tempDocSize).percentage[ fit_or_fill ]; 396 | var placedPercentage = calculateNewSize( [image_width, image_height], targetSize).percentage[ fit_or_fill ]; 397 | imageLayer.resize( eqSize, eqSize, AnchorPosition.MIDDLECENTER ); 398 | image_width = tempDocSize[0]; 399 | image_height = tempDocSize[1]; 400 | 401 | } 402 | 403 | var imageSize = [ image_width, image_height ]; 404 | var newSize = calculateNewSize(imageSize, targetSize).percentage[ fit_or_fill ]; 405 | var imageOverflowsTarget = newSize <= 100; 406 | 407 | var percentageString = ''; 408 | if ( placedPercentage ) { 409 | percentageString = placedPercentage === 100 ? 100 : '~'+Math.round( placedPercentage ); 410 | } 411 | else { 412 | percentageString = newSize === 100 ? 100 : '~'+Math.round( newSize ); 413 | } 414 | 415 | if ( isVector ) noUpsize = false; 416 | 417 | if ( noUpsize && imageOverflowsTarget || !noUpsize ) { 418 | imageLayer.resize( newSize, newSize, AnchorPosition.MIDDLECENTER ); 419 | if ( changeLayerName === 'always' ) { 420 | renameActiveLayer(' (Size: '+ percentageString +'%)'); 421 | } 422 | } 423 | else { 424 | if ( changeLayerName && changeLayerName !== 'never' ) { 425 | renameActiveLayer( ' (Upsize prevented: '+ percentageString +'%)' ); 426 | } 427 | } 428 | 429 | } 430 | 431 | function activateDocumentByID( docId ) { 432 | var ref = new ActionReference(); 433 | var desc = new ActionDescriptor(); 434 | ref.putIdentifier(charIDToTypeID('Dcmn'), docId); 435 | desc.putReference(charIDToTypeID('null'), ref); 436 | try { executeAction( charIDToTypeID( "slct" ), desc, DialogModes.NO ); } catch(e) {} 437 | } 438 | 439 | function renameActiveLayer( newName ) { 440 | 441 | var activeLayer = app.activeDocument.activeLayer; 442 | activeLayer.name = activeLayer.name + newName; 443 | } 444 | 445 | function calculateNewSize( inputSize, targetSize ) { 446 | function mathMax( array ) { return array[0] > array[1] ? array[0] : array[1]; } 447 | function mathMin( array ) { return array[0] < array[1] ? array[0] : array[1]; } 448 | var sizeArray = [ targetSize[0] / inputSize[0], targetSize[1] / inputSize[1] ]; 449 | var ratioFit = mathMin( sizeArray ); 450 | var ratioFill = mathMax( sizeArray ); 451 | return { 452 | pixels: { 453 | fit: { width: inputSize[0]*ratioFit, height: inputSize[1]*ratioFit }, 454 | fill: { width: inputSize[0]*ratioFill, height: inputSize[1]*ratioFill } 455 | }, 456 | percentage: { 457 | fit: (100 / inputSize[0]) * (inputSize[0]*ratioFit), 458 | fill: (100 / inputSize[0]) * (inputSize[0]*ratioFill) 459 | } 460 | }; 461 | } 462 | 463 | function getTargetBounds( doc, activeLayer ) { 464 | 465 | // Set selection as false, if bounds are not found. 466 | var bounds; 467 | if ( hasSelection ) { 468 | bounds = doc.selection.bounds; 469 | } 470 | else { 471 | var clippingMaskBase = findClippingMask( doc, activeLayer ); 472 | // var clippingMaskBase = addToClippingMask( doc, activeLayer ); 473 | if ( clippingMaskBase !== false ) { 474 | bounds = clippingMaskBase.boundsNoEffects; 475 | } 476 | else { 477 | bounds = activeLayer.boundsNoEffects; 478 | } 479 | } 480 | 481 | var width = bounds[2].value - bounds[0].value; 482 | var height = bounds[3].value - bounds[1].value; 483 | 484 | return { 485 | bounds: bounds, 486 | width: bounds[2].value - bounds[0].value, 487 | height: bounds[3].value - bounds[1].value, 488 | }; 489 | 490 | } 491 | 492 | function align( imageLayer, targetBounds ) { 493 | 494 | var imageBounds = imageLayer.boundsNoEffects; 495 | 496 | var image = { 497 | offset: { 498 | top: imageBounds[1].value, 499 | right: imageBounds[2].value, 500 | bottom: imageBounds[3].value, 501 | left: imageBounds[0].value, 502 | }, 503 | }; 504 | var target = { 505 | offset: { 506 | top: targetBounds[1].value, 507 | right: targetBounds[2].value, 508 | bottom: targetBounds[3].value, 509 | left: targetBounds[0].value, 510 | }, 511 | }; 512 | 513 | var image_width = image.offset.right - image.offset.left; 514 | var image_height = image.offset.bottom - image.offset.top; 515 | 516 | var target_width = target.offset.right - target.offset.left; 517 | var target_height = target.offset.bottom - target.offset.top; 518 | 519 | var translateX = target.offset.left - image.offset.left - ( image_width/2 ) + ( target_width/2 ); 520 | var translateY = target.offset.top - image.offset.top - ( image_height/2 ) + ( target_height/2 ); 521 | imageLayer.translate( translateX, translateY ); 522 | 523 | } 524 | 525 | function selectionExists() { 526 | 527 | var selection = false; 528 | try { selection = app.activeDocument.selection.bounds; } catch(e) {} 529 | 530 | return selection; 531 | 532 | } 533 | 534 | // Returns the base layer in a clipping mask 535 | function findClippingMask( doc, layer ) { 536 | 537 | // Layer is in a clipping mask... 538 | if ( layer.grouped ) { 539 | 540 | while ( doc.activeLayer.grouped ) { selectLayer('below'); } 541 | var clippingMaskBase = doc.activeLayer; 542 | 543 | // When the clipping mask base is grouped, all layers involved in the clipping mask are grouped... 544 | app.runMenuItem( stringIDToTypeID('groupLayersEvent') ); 545 | var tempGroup = doc.activeLayer; 546 | var newLayer = doc.artLayers.add(); 547 | newLayer.move( tempGroup, ElementPlacement.INSIDE); 548 | newLayer.grouped = true; // Make the empty layer part of the clipping mask 549 | doc.activeLayer = tempGroup; 550 | app.runMenuItem( stringIDToTypeID('ungroupLayersEvent') ); 551 | doc.activeLayer = newLayer; 552 | if ( method === 'place' ) clipTempLayer = newLayer; 553 | 554 | return clippingMaskBase; 555 | 556 | } 557 | // Layer is not in a clipping mask... but it could still be the base layer of a clipping mask 558 | else if ( !layer.grouped ) { 559 | 560 | // When the clipping mask base is grouped, all layers involved in the clipping mask are grouped... 561 | // Here we still don't know if this is the clipping mask base though... 562 | app.runMenuItem( stringIDToTypeID('groupLayersEvent') ); 563 | 564 | var tempGroup = doc.activeLayer, 565 | tempGroupLayers = tempGroup.layers, 566 | tempGroupLayersLength = tempGroupLayers.length; 567 | 568 | // When you group clipping mask base layer, it groups all the layers in that clipping mask. 569 | // So if the newly created group has more than one layer, the first active layer or the first layer of that group is the base layer. 570 | if ( tempGroupLayersLength > 1 ) { 571 | var clippingMaskBase = tempGroupLayers[ tempGroupLayersLength - 1 ]; 572 | var newLayer = doc.artLayers.add(); 573 | newLayer.move( tempGroup, ElementPlacement.INSIDE); 574 | newLayer.grouped = true; // Make the empty layer part of the clipping mask 575 | doc.activeLayer = tempGroup; 576 | app.runMenuItem( stringIDToTypeID('ungroupLayersEvent') ); 577 | doc.activeLayer = newLayer; 578 | if ( method === 'place' ) clipTempLayer = newLayer; 579 | 580 | return clippingMaskBase; 581 | 582 | } 583 | // False alarm... No clipping masks here. 584 | else { 585 | app.runMenuItem( stringIDToTypeID('ungroupLayersEvent') ); 586 | return false; 587 | } 588 | 589 | } 590 | 591 | } 592 | 593 | function selectLayer( direction ) { 594 | 595 | direction = charIDToTypeID( direction === 'above' ? "Frwr" : "Bckw" ); 596 | 597 | try { 598 | // ======================================================= 599 | var idslct = charIDToTypeID( "slct" ); 600 | var desc4110 = new ActionDescriptor(); 601 | var idnull = charIDToTypeID( "null" ); 602 | var ref750 = new ActionReference(); 603 | var idLyr = charIDToTypeID( "Lyr " ); 604 | var idOrdn = charIDToTypeID( "Ordn" ); 605 | ref750.putEnumerated( idLyr, idOrdn, direction ); 606 | desc4110.putReference( idnull, ref750 ); 607 | var idMkVs = charIDToTypeID( "MkVs" ); 608 | desc4110.putBoolean( idMkVs, false ); 609 | var idLyrI = charIDToTypeID( "LyrI" ); 610 | var list325 = new ActionList(); 611 | list325.putInteger( 22 ); 612 | desc4110.putList( idLyrI, list325 ); 613 | executeAction( idslct, desc4110, DialogModes.NO ); 614 | } catch (e) {} 615 | 616 | } 617 | 618 | function dialog() { 619 | 620 | /* 621 | Code for Import https://scriptui.joonas.me — (Triple click to select): 622 | {"items":{"item-0":{"id":0,"type":"Dialog","parentId":false,"style":{"text":"Paste or place inside selection.jsx","preferredSize":[0,0],"margins":30,"orientation":"column","spacing":15,"alignChildren":["fill","top"],"varName":null}},"item-2":{"id":2,"type":"Button","parentId":6,"style":{"text":"1. Fill","justify":"center","preferredSize":[0,0],"alignment":null,"varName":"pasteFill","helpTip":null}},"item-6":{"id":6,"type":"Panel","parentId":17,"style":{"varName":null,"text":"Paste","preferredSize":[0,0],"margins":25,"orientation":"column","spacing":10,"alignChildren":["fill","top"],"alignment":null}},"item-12":{"id":12,"type":"Button","parentId":6,"style":{"text":"2. Fit","justify":"center","preferredSize":[0,0],"alignment":null,"varName":"pasteFit","helpTip":null}},"item-13":{"id":13,"type":"Panel","parentId":17,"style":{"varName":null,"text":"Place","preferredSize":[0,0],"margins":25,"orientation":"column","spacing":10,"alignChildren":["fill","top"],"alignment":null}},"item-14":{"id":14,"type":"Button","parentId":13,"style":{"text":"3. Fill","justify":"center","preferredSize":[0,0],"alignment":null,"varName":"placeFill","helpTip":null}},"item-15":{"id":15,"type":"Button","parentId":13,"style":{"text":"4. Fit","justify":"center","preferredSize":[0,0],"alignment":null,"varName":"placeFit","helpTip":null}},"item-16":{"id":16,"type":"Panel","parentId":0,"style":{"varName":null,"text":"Info","preferredSize":[0,0],"margins":25,"orientation":"column","spacing":10,"alignChildren":["left","top"],"alignment":null}},"item-17":{"id":17,"type":"Group","parentId":0,"style":{"varName":null,"preferredSize":[0,0],"margins":0,"orientation":"row","spacing":20,"alignChildren":["left","fill"],"alignment":null}},"item-18":{"id":18,"type":"StaticText","parentId":16,"style":{"varName":null,"text":"Use number keys as shortcuts \nfor each function. Space toggles\nthe upsizing option.","justify":"left","preferredSize":[0,0],"alignment":null,"helpTip":null}},"item-19":{"id":19,"type":"Panel","parentId":0,"style":{"varName":null,"text":"Options","preferredSize":[0,0],"margins":25,"orientation":"column","spacing":10,"alignChildren":["left","top"],"alignment":null}},"item-20":{"id":20,"type":"Checkbox","parentId":19,"style":{"varName":"noUpsizing","text":"Don't upsize past original size","preferredSize":[0,0],"alignment":null,"helpTip":null}}},"order":[0,17,6,2,12,13,14,15,19,20,16,18],"activeId":18} 623 | */ 624 | 625 | // DIALOG 626 | // ====== 627 | var dialog = new Window("dialog"); 628 | dialog.text = "Paste or place inside selection.jsx"; 629 | dialog.orientation = "column"; 630 | dialog.alignChildren = ["fill","top"]; 631 | dialog.spacing = 15; 632 | dialog.margins = 30; 633 | 634 | // GROUP1 635 | // ====== 636 | var group1 = dialog.add("group"); 637 | group1.orientation = "row"; 638 | group1.alignChildren = ["left","fill"]; 639 | group1.spacing = 20; 640 | group1.margins = 0; 641 | 642 | // PANEL1 643 | // ====== 644 | var panel1 = group1.add("panel"); 645 | panel1.text = "Paste"; 646 | panel1.orientation = "column"; 647 | panel1.alignChildren = ["fill","top"]; 648 | panel1.spacing = 10; 649 | panel1.margins = 25; 650 | 651 | var pasteFill = panel1.add("button"); 652 | pasteFill.text = "1. Fill"; 653 | pasteFill.justify = "center"; 654 | 655 | var pasteFit = panel1.add("button"); 656 | pasteFit.text = "2. Fit"; 657 | pasteFit.justify = "center"; 658 | 659 | // PANEL2 660 | // ====== 661 | var panel2 = group1.add("panel"); 662 | panel2.text = "Place"; 663 | panel2.orientation = "column"; 664 | panel2.alignChildren = ["fill","top"]; 665 | panel2.spacing = 10; 666 | panel2.margins = 25; 667 | 668 | var placeFill = panel2.add("button"); 669 | placeFill.text = "3. Fill"; 670 | placeFill.justify = "center"; 671 | 672 | var placeFit = panel2.add("button"); 673 | placeFit.text = "4. Fit"; 674 | placeFit.justify = "center"; 675 | 676 | // PANEL3 677 | // ====== 678 | var panel3 = dialog.add("panel"); 679 | panel3.text = "Options"; 680 | panel3.orientation = "column"; 681 | panel3.alignChildren = ["left","top"]; 682 | panel3.spacing = 10; 683 | panel3.margins = 25; 684 | 685 | var noUpsizing = panel3.add("checkbox"); 686 | noUpsizing.text = "Don't upsize past original size"; 687 | 688 | // PANEL4 689 | // ====== 690 | var panel4 = dialog.add("panel"); 691 | panel4.text = "Info"; 692 | panel4.orientation = "column"; 693 | panel4.alignChildren = ["left","top"]; 694 | panel4.spacing = 10; 695 | panel4.margins = 25; 696 | 697 | var statictext1 = panel4.add("group"); 698 | statictext1.orientation = "column"; 699 | statictext1.alignChildren = ["left","center"]; 700 | statictext1.spacing = 0; 701 | 702 | statictext1.add("statictext", undefined, "Use number keys as shortcuts "); 703 | statictext1.add("statictext", undefined, "for each function. Space toggles"); 704 | statictext1.add("statictext", undefined, "the upsizing option."); 705 | 706 | // CUSTOM EVENTS 707 | 708 | noUpsizing.active = true; 709 | noUpsizing.value = 1; 710 | panel4.enabled = false; // So that it's there, but doesn't steal the thunder of anything else 711 | 712 | // PASTE FILL 713 | pasteFill.onClick = function() { 714 | method = 'paste'; 715 | fit_or_fill = 'fill'; 716 | noUpsize = noUpsizing.value; 717 | dialog.close(); 718 | } 719 | // PASTE FIT 720 | pasteFit.onClick = function() { 721 | method = 'paste'; 722 | fit_or_fill = 'fit'; 723 | noUpsize = noUpsizing.value; 724 | dialog.close(); 725 | } 726 | // PLACE FILL 727 | placeFill.onClick = function( keyName ) { 728 | method = 'place'; 729 | fit_or_fill = 'fill'; 730 | noUpsize = noUpsizing.value; 731 | dialog.close(); 732 | } 733 | // PLACE FILL 734 | placeFit.onClick = function() { 735 | method = 'place'; 736 | fit_or_fill = 'fit'; 737 | noUpsize = noUpsizing.value; 738 | dialog.close(); 739 | } 740 | 741 | dialog.addEventListener("keyup", function( key ) { 742 | 743 | if ( key.keyName == 1 ) { 744 | pasteFill.onClick(); 745 | } 746 | else if ( key.keyName == 2 ) { 747 | pasteFit.onClick(); 748 | } 749 | else if ( key.keyName == 3 ) { 750 | placeFill.onClick( key.keyName ); 751 | } 752 | else if ( key.keyName == 4 ) { 753 | placeFit.onClick(); 754 | } 755 | else if ( key.keyName == 'Space' ) { 756 | noUpsizing.value = noUpsizing.value ? 0 : 1; 757 | } 758 | 759 | }); 760 | 761 | dialog.show(); 762 | 763 | } 764 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Photoshop Script: Paste or Place Inside Selection.jsx 2 | 3 | The scripts helps you paste or place images using fit and fill methods. Example gifs in [usage](#usage). 4 | 5 | ![](readme-images/paste-or-place-inside-selection-dialog.png) 6 | 7 | ## Usage 8 | 9 | The script has two starting points for different situations: 10 | 11 | 1. **[Selection method (gif)](readme-images/selection-method.gif):** If you have an active marquee selection in the document, the image is placed inside the selection on a new layer. 12 | 2. **[Active layer method (gif)](readme-images/active-layer-method.gif):** If you don't have an active marquee selection, the image is placed in a new layer and placed in a clipping mask with the active layer. 13 | - If you want to place inside an existing clipping mask, you can select any layer that is part of that clipping mask. The new image will be placed on top of that stack. Just make sure the base layer of that clipping mask is not hidden. 14 | 15 | ## Known issues 16 | - If the base layer of a clipping mask is hidden, the script will fail. It's related to detecting the "bounds" of the clipping mask. This could be improved, but I don't think that is much of an issue, so I have no plans to fix it. The active layer can be hidden as long as it's not already in a clipping mask though. 17 | 18 | ## Good to know... 19 | - Only tested in PS CC 20 | - There is a feature where the current layer size (in percentages) is appended to the layer name. 21 | - The variable that controls this is called "changeLayerName". Default value: "always". 22 | - Optional values: 'upsize prevented', 'never' 23 | - You should definitely set a shortcut to launch this script or otherwise it'll be too difficult to use frequently. 24 | - The old name was "Place Inside Selection.jsx". 25 | -------------------------------------------------------------------------------- /readme-images/active-layer-method.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joonaspaakko/paste-or-place-inside-selection-photoshop-script/f03eeedae66c111ac7c8756decea64ed77cbd8a7/readme-images/active-layer-method.gif -------------------------------------------------------------------------------- /readme-images/paste-or-place-inside-selection-dialog.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joonaspaakko/paste-or-place-inside-selection-photoshop-script/f03eeedae66c111ac7c8756decea64ed77cbd8a7/readme-images/paste-or-place-inside-selection-dialog.png -------------------------------------------------------------------------------- /readme-images/selection-method.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joonaspaakko/paste-or-place-inside-selection-photoshop-script/f03eeedae66c111ac7c8756decea64ed77cbd8a7/readme-images/selection-method.gif --------------------------------------------------------------------------------