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

The path aligns with the route, yet the component designated for that route fails to render

I wrote a React component named Workout that looks like this: const Workout = props => { console.log(props); return ( <div> <h1>hello</h1> </div> ); }; export default Workout; Next, I imported this componen ...

Dealing with data manipulation in the realm of javascript

In the following code snippet, I am iterating through multiple URLs and extracting data (title and content) from each of them. My objective is to store this data for later use on another page, and thus it needs to be accessible using its respective title, ...

ReactJS experiencing issue with the functionality of the all-the-cities library

Encountering an issue where importing the library all-the-cities causes reactjs to malfunction and display the following error: TypeError: fs.readFileSync is not a function (anonymous function) C:myproject/node_modules/all-the-cities/index.js:6 3 | cons ...

Error encountered while running a mounted hook in Vue.js that was not properly handled

I have created a To Do List app where users can add tasks using a button. Each new task is added to the list with a checkbox and delete button next to it. I want to save all the values and checked information on the page (store it) whenever the page is ref ...

How to Stop Form from Automatically Submitting in Laravel 5.5 and vue-typeahead's onHit method

I have integrated the vue-typeahead component into my Laravel project using vue-typeahead. However, I am facing an issue where when I select an entry from the result list by pressing the "enter" key, the form automatically submits. Is there a way to preve ...

My goal is to display the products on the dashboard that have a quantity lower than 10. This information is linked to Firestore. What steps can I take to enhance this functionality?

{details.map((val, colorMap, prodName) => { I find myself a bit perplexed by the conditional statement in this section if( colorMap < 10 ){ return ( <ul> <li key= ...

React/React Hooks: Want to initiate input validation when a user deselects a checkbox

Currently, my component includes an input field and a checkbox. When the checkbox is checked, it disables the input field and clears any validation errors. However, I want to add functionality so that if the checkbox is unchecked, the input field becomes ...

Guide to converting a specific tag into div using Javascript

I am working with some HTML code that includes a div: <div class="myDiv"> <a href="" title="">My link</a> <p>This is a paragraph</p> <script>//This is a script</script> </div> Additionally, I ha ...

Utilizing JQUERY and AJAX for conditional statements

I am currently in the process of creating a basic chat bot. At this point, the bot replies when the user inputs a pre-defined question. However, I am trying to figure out how to program the chatbot to respond with a "sorry, I don't understand" message ...

What is the best approach for managing Promise rejections in Jest test scenarios?

Currently, I am engaged in a node JS project where my task is to write test cases. Below is the code snippet that I am working on - jest.mock('../../utils/db2.js') const request = require('supertest') const executeDb2Query = require(&ap ...

Improve the functionality of select[multiple] to allow for single-click modifications without the need for CMD/CTRL

I am attempting to modify the default functionality of a select element so that clicking once on its options changes their selected state. Essentially, I want to eliminate the confusing requirement of holding down shift/ctrl to select multiple options. I ...

What are the steps for initializing a session in Vue.js with Django upon a successful login?

Upon successful login, I want to redirect to a page indicating success and also include a session. How can this be achieved? I am using HTML with Vue.js for the front end and Django for the back end. Below is my Vue.js script for the login: <script> ...

Updating the @mui/x-data-grid table dynamically upon fetching new data

Seeking assistance regarding updating data in the DataGrid component from the @mui/x-data-grid module within a React application. Specifically, I am facing challenges in refreshing the table after retrieving data from an API using react-query. Despite succ ...

Execute the function on the React template rendering process

How can I ensure that the getQuestions function is called when the template questionsCollected is rendered, without relying on an event trigger like onClick? The ajax call successfully retrieves the option items and logs them to the console. The template ...

What is the best way to share image data between pages in Next.js?

I'm currently developing a project that mimics Instagram (simply because I want to explore Next.js further) and I'm looking for a way to handle image uploads. My goal is to allow users to upload their images and then redirect them to the "create ...

NextJS will redirect the user back to the previous router they came from following authentication

Hello! I am currently facing a challenge in redirecting a user back to the initial page they clicked on after being authenticated. The issue lies in server-side rendering (SSR) and the lack of access to the window.history object in getServerSideProps. The ...

Execute a setInterval operation, pause it for a duration of 3 seconds, and then resume its execution

A setInterval function is looping through some div classes, and if it encounters a div with a specific class, it should pause for 3 seconds before resuming. I am using the following code to clear the interval: clearInterval(myInterval); However, I nee ...

Error: This Service Worker is restricted to secure origins only due to a DOMException

Having trouble implementing this on my website; it keeps showing the following error. Help, please! Service Worker Error DOMException: Only secure origins are allowed. if ('serviceWorker' in navigator && 'PushManager' in wind ...

Tips for maximizing the efficiency of a callback when utilizing the filter function in Primefaces for 'myDataTable'

Currently using Primefaces 5.1, and I've encountered a situation where I want to hide a table until after the filter is applied in Javascript. My initial thought was to simply set the css of the table to visibility:hidden;, followed by running the fol ...

ES6 Conditional Import and Export: Leveraging the Power of Conditional

Looking to implement a nested if else statement for importing and exporting in ES6? In this scenario, we have 2 files - production.js and development.js which contain keys for development and production code respectively. Additionally, there is another fil ...