Adjust scale sizes of various layers using a script

I have created a script in Photoshop to adjust the scale size of multiple layers, but I am encountering some inaccuracies. The script is designed to resize both the width and height of the selected layers to 76.39%. However, when testing the script, I found that the width changed to 76.92% and the height changed to 75.76% instead.

What could be causing this discrepancy in the script? It is crucial to maintain the aspect ratio while scaling the layers.

// Script for resizing multiple layers
function resizeSelectedLayers() {
    var doc = app.activeDocument;
    var selectedLayers = [];

    // Prompt user to select layers
    var selectedLayerIndices = prompt("Enter the indices of the layers you want to resize (comma-separated):", "");
    if (selectedLayerIndices === null || selectedLayerIndices === "") {
        alert("No layers selected.");
        return;
    }

    // Convert comma-separated indices to array
    var indicesArray = selectedLayerIndices.split(",");
    for (var i = 0; i < indicesArray.length; i++) {
        var index = parseInt(indicesArray[i]);
        if (!isNaN(index) && index >= 0 && index < doc.layers.length) {
            selectedLayers.push(doc.layers[index]);
        } else {
            alert("Invalid layer index: " + indicesArray[i]);
            return;
        }
    }

    // Check if there are selected layers
    if (selectedLayers.length > 0) {
        // Resize each selected layer
        for (var j = 0; j < selectedLayers.length; j++) {
            var selectedLayer = selectedLayers[j];
            doc.activeLayer = selectedLayer;

            // Calculate scaling factor
            var scalePercentage = 76.39;
            var scaleFactor = scalePercentage / 100;

            // Get current dimensions
            var width = selectedLayer.bounds[2] - selectedLayer.bounds[0];
            var height = selectedLayer.bounds[3] - selectedLayer.bounds[1];

            // Calculate new dimensions with locked aspect ratio
            var newWidth = width * scaleFactor;
            var newHeight = height * scaleFactor;

            // Calculate the scaling ratio
            var ratio = newWidth / width;

            // Set up transformation parameters
            var desc = new ActionDescriptor();
            var ref = new ActionReference();
            ref.putEnumerated(charIDToTypeID('Lyr '), charIDToTypeID('Ordn'), charIDToTypeID('Trgt'));
            desc.putReference(charIDToTypeID('null'), ref);

            // Set transformation values
            desc.putEnumerated(charIDToTypeID('FTcs'), charIDToTypeID('QCSt'), charIDToTypeID('Qcsa'));
            desc.putUnitDouble(charIDToTypeID('Wdth'), charIDToTypeID('#Prc'), 100 * ratio);
            desc.putUnitDouble(charIDToTypeID('Hght'), charIDToTypeID('#Prc'), 100 * ratio);
            desc.putEnumerated(charIDToTypeID('Intr'), charIDToTypeID('Intp'), charIDToTypeID('Bcbc'));

            // Execute transformation
            executeAction(charIDToTypeID('Trnf'), desc, DialogModes.NO);
        }
    } else {
        alert("Please select one or more layers.");
    }
}

// Ensure there is an active document
if (app.documents.length > 0) {
    // Call the resizeSelectedLayers function
    resizeSelectedLayers();
} else {
    alert("No documents are open.");
}

Answer №1

Consider a basic example: look at this 3 x 4 pixel image:

https://i.stack.imgur.com/fkwP9.png

If you enlarge it by 150%, the dimensions would be 4.5 x 6 pixels. However, Photoshop cannot handle partial pixels, so it smooths out the scaled image and utilizes a total of 5 x 6 pixels (or 166.67% x 150%)

https://i.stack.imgur.com/DhR76.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using a percentage width on a <div> element with the "overflow-x: scroll" property does not seem to be functioning properly, even when encapsulated within

My code includes a div within another div, taking up 50% of the page's width: <div id="mainContainer" class="mainContainer"> <div id="scroller" class="scrolling"> <!-- items here should make the div really long --> & ...

Preserve the ajax controls while uploading files

I encountered a minor issue with file uploading. When I click the upload button, a window (ajax powered) pops up for selecting a file. However, as soon as the file is uploaded to the browser, the page reloads and the window closes, leaving me without the ...

Encountering invalid parameters while attempting to utilize the track.scrobble service from the Last.Fm API in a Node.js application

After successfully completing the Last.Fm authentication process following the instructions provided here, I received the session key without any issues. However, my attempts to make an authenticated POST request to the track.scrobble method of the Last.Fm ...

The issue with session storage persisting even after closing the iframe

Encountering a persistent issue where the sessionStorage remains populated even after closing an iframe and opening another one with the same destination. I assumed that the sessionStorage would be reset and start afresh each time. The iframe is contained ...

Struggling to master YAML integration with Google App Engine?

Seeking assistance with YAML as I am new to it: application: baking-tutorial version: secureable runtime: python27 api_version: 1 threadsafe: true handlers: - url: /robots\.txt static_files: static/robots.txt upload: static/robots\.txt - url: ...

Unexpected behavior observed when trying to smoothly scroll to internal links within a div, indicating a potential problem related to CSS dimensions and

Within a series of nested div containers, I have one with the CSS property overflow:hidden. My goal is to smoothly scroll to internal links within this specific div using jQuery. The snippet of code below has worked successfully in previous projects: ...

Ways to verify if the CSS background-color is set to white?

I am looking for a solution: $('*').click(function() { if($(this).css("background-color") == "#ffffff") { $(this).css("background-color") == "#000000" } });​​​​ that will execute on click of a specific cla ...

Obtaining an image from a URL, saving it, and then animating it? That definitely

Looking to create a dynamic animation with images that update every 15 minutes from the following URL: How should I go about storing and looping through the most recent 24 images for the animation? Is using a MySQL database the best option or are there o ...

What steps can I take to persistently subscribe to SignalR from an Angular service even in the event of connection failures?

Is there a way to safely attempt to connect to SignalR with intervals between attempts until the connection is established? Also, does anyone have advice on how to handle the different stages of connectivity to the web sockets effectively? We are utilizin ...

Finding elements based on their position using Javascript

I'm searching for an optimal method to identify all elements located within a specific range of pixels from the top of the page. Currently, I have implemented a straightforward test called inRange function inRange(el, from, to) { var top = el.offs ...

Is there a way to embed HTML code within a JavaScript variable?

Embedding HTML code within Java Flow can be quite interesting For instance: Check out this JSFiddle link And here's how you can incorporate it into your script: widget.value += ""; Generating a Pro Roseic Facebook POP-UP Box through Widg ...

Utilizing the Pub/Sub architecture to integrate the kafka-node library within Node Js

Utilizing the kafka-node module in my NodeJs Microservise project, I am aiming to implement a Pub/Sub (publisher and subscriber) design pattern within the Functional programming paradigm. producer.js const client = new kafka.KafkaClient({ kafkaHost: ...

Can you explain the functioning of knockout container less syntax? (does it have any drawbacks?)

There are numerous instances and examples of using knockout ContainerLess syntax, although I find it challenging to locate proper documentation from their site. Initially, my question was "is it evil?" but upon realizing my lack of understanding on how it ...

The error "localStorage is not defined when using an axios interceptor in NextJS"

Within my root directory, there lies a file named api.js. This particular file is responsible for managing calls to an external API, with a focus on request and response interceptors. One specific use case involves injecting the access_token, leading to th ...

Map failing to refresh

Having some trouble with the map function as it's not updating my select box with the new selected value. The issue occurs within a material UI dialog that appears when viewing a file. I notice that the values get updated only after closing and reopen ...

A guide on executing a double click action on an element in Selenium Webdriver with JavaScript specifically for Safari users

Having trouble double clicking an element in Safari using Java / Webdriver 2.48. All tests work fine on IE, Chrome, and Firefox but Safari does not support Actions. Currently attempting: executor.executeScript("arguments[0].dblclick();", element); or ...

How to display a conditional component in a single line with Material UI

I'm facing an issue with a component that is being reused multiple times. Here's the current output: |MyComponent1| |MyComponent2| Specifically, my condition is: if (a == 'One' || b == 'Two'){ <MyComponent data={data}/> ...

What is the most effective way to transmit multiple pieces of server-side data to JavaScript?

Imagine having multiple Javascript codes embedded in pages. Currently, it's simple to initialize variables by using Print/Echo statements to set JavaScript values. For example: var x = <?php echo('This is a value');?> Initially, I co ...

Spin the text inside an <li> element generated by JavaScript

I am currently working on a unique script designed to create a custom number of slices for a circle. The items in the circle are being displayed as shown in this generated circle image. This is the Javascript code I have been using: for () { men ...

The value returned is undefined when using getStaticProps

Recently, while working on my project with Next.js, I encountered an issue where I was trying to access data but kept getting undefined. Below is the code snippet that I was working with: function Home({books}) { console.log(books) return <div>Home ...