The highest and lowest points of the visible image within a transparent PNG file

As a newcomer to Three.js and graphics in general, I've been on the lookout for a method to identify the highest and lowest visible points in a PNG image with transparency. I understand that graphics manipulation involves manipulating an array of pixels, so my approach would be to iterate through this array to find non-transparent pixels with the maximum and minimum y-axis values. Is there a specific feature in Three.js or perhaps even pure Javascript that can grant me access to this data (pixel array)? Alternatively, does the library offer a more direct way to achieve my objective?

The ultimate goal here is to vertically align the image based on its visible content.

Thank you!

- UPDATE -

Following @Paul Green's advice, I searched for material related to getImageData in Three.js, which is used to extract a pixel array from a canvas context. My intention was to find a similar function within Three.js without involving the canvas element since my script doesn't utilize it. I'm seeking a solution that allows me to gather information before rendering the image. The idea of a Three.js dataTexture seems promising, but I still need more clarity on how to implement it. Any guidance on this matter would be greatly appreciated!

Answer №1

To extract pixel information from an image, you can utilize the approach outlined in this solution: How to retrieve a pixel's data using JavaScript or jQuery when interacting with it on screen?

var img = new Image();
img.src = 'image.jpg';
var context = document.getElementById('canvas').getContext('2d');
context.drawImage(img, 0, 0);
data = context.getImageData(x, y, 1, 1).data;

Following this, iterate through the array of pixels and examine for the specified threshold value. A fully transparent pixel is denoted by 0, whereas a fully opaque one is represented by 255.

This referenced question may further guide you on how to access a particular color channel: How to obtain a pixel from an HTML Canvas?

Note that pix[i+3] contains the alpha channel in the provided example.

The current position of the pixel can be determined by dividing the loop iteration number by the width, giving you the height index.

For instance, if your image dimensions are 200x50 px, encountering a non-transparent pixel at iteration 534 would mean moving 2 pixels down on the Y-axis (534/200 = 2) and calculating the remaining distance along the X-axis with 534 mod 200.

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

Is it possible to stop the manipulation of HTML and CSS elements on a webpage using tools similar to Firebug?

How can we prevent unauthorized editing of HTML and CSS content on a webpage using tools like Firebug? I have noticed that some users are altering values in hidden fields and manipulating content within div or span tags to their advantage. They seem to be ...

Passing data between functions in a JavaScript file

I need some guidance on implementing an angularjs google column chart. Specifically, I have a requirement to transfer the value from one JavaScript function to another variable defined in a separate JavaScript function. Here is an example snippet of code ...

Utilize esbuild to monitor for any modifications, recompile the code, and automatically restart the express server

In my endeavor to develop a basic SSR-powered project using express + react, I find the need to monitor frontend and backend scripts concurrently in the development process. The primary objective is to utilize express routes in directing to react page com ...

Guide to encoding data using a multidimensional array in JSON format

I have an array that looks like this: array { [0] => {"ID":"343","name":"John","money":"3000"} [1] => {"ID":"344","name":"Erik","money":"2000"} [2] => {"ID":"346","name":"Ronny","money":"3300"} } My goal is to transfer this data from ...

Refreshing a node in Jqgrid Treegrid by updating the local source data

I have constructed a Treegrid using local data $("#historyGrid").jqGrid({ datatype: "jsonstring", datastr : treeGridObject , colNames:["Id","Channel","Current","History","Delta"], colModel:[ {name:'id', index:'Id&apo ...

The simplest way to increase the size of a child element in order to generate a scrollable area

When working with HTML, it's important to consider how the size of a child div affects the parent div. If the child div is larger than its parent, scrollbars will appear on the parent div if the appropriate style rules are set. However, I'm inte ...

Analyzing bitmap header

I have a couple of inquiries regarding the BITMAPFILEHEADER structure. Firstly, I find it intriguing that if we were to create our own version of the BITMAPFILEHEADER structure, it would take up 16 bytes due to Data Structure Alignment. However, the origi ...

Enhance the speed of webview on Android devices

I have been working on an application that utilizes a webview to load both HTML and JavaScript files. Unfortunately, I have noticed a significant decrease in performance when displaying the content. Despite trying various solutions such as: webVi ...

Angular rxjs: Wait for another Observable to emit before subscribing

My setup involves having 2 subscriptions - one is related to my ActivatedRoute, and the other is from ngrx Store. ngOnInit() { this.menuItems$ = this.store.select('menuItems'); this.menuItems$.subscribe(data => { this.menuItem ...

End node.js once and for all

After starting my server using forever start start.js It ran normally. However, when I attempted to stop it with forever stopall The server was removed from forever list as expected Nevertheless, upon running lsof -i tcp:3000, my server still showed u ...

Utilizing AJAX to amplify the worth of plupload's echo capabilities

Greetings! Here is the JavaScript code I am using for plupload var uploader = new plupload.Uploader({ runtimes : 'html5,flash,silverlight,html4', browse_button : 'pickfiles', // you can pass in id... container: document.getElementById( ...

How to store selected checkbox values in an array using AngularJS

Check out this code snippet: <tr ng-repeat="doc in providers"> <td><input type="checkbox" ng-true-value="{{doc.provider.Id}}" ng-false-value="" ng-model="ids"></td> </tr> {{ids}} I am trying to store the values of ...

Disabling keypress function in onKeyPress, yet onChange event still activates

In my ReactJS component, I have implemented a function that is triggered by the onKeyPress event: onKeyPress(e) { if (!isNumeric(e.key) && e.key !== '.') { return false; } } Although this function successfully prevents non-numer ...

Is there a way to change my cursor to a pointer finger when hovering over my box?

<script type="text/javascript"> function draw() { var canvas = document.getElementById('Background'); if (canvas.getContext) { var ctx = canvas.getContext('2d'); ctx.lineWidth = 0.4 ctx.strokeRect(15, 135, 240, 40) Is there a w ...

Unable to set height of images using jQuery following an ajax request

I have a function that determines the highest image height to set as the minimum height of the image container element, specifically a figure. Initially, the function works well on window load and when the window is resized. However, after an ajax call lo ...

Share your ES module (.mjs) on NPMJS with support for Node versions older than 8.5.0 (Dual Package)

In the past, publishing a module written in ES6 to NPMJS was a simple process: transpile the code using Babel and publish the resulting `lib` directory to NPMJS while keeping the original `src` files on GitHub. However, with Node v8.5.0's experimenta ...

Issue with variable not being refreshed within requestJS's data event

I have been attempting to store the response from a URL in a variable for caching purposes and then send it upon subsequent requests. I am currently writing to the variable during the data event of the request. The variable does get updated, but I am encou ...

Indeed, yet another problem with clearInterval

I could use some assistance as I am currently stuck trying to figure out why the stopTimer() function is not working correctly. Any guidance or suggestions would be highly appreciated. Thank you! http://jsfiddle.net/4Efbd/1/ var counter; function endTim ...

Transmit ByteArray to JavaScript

Is there a way to send a jpg image as a ByteArray from ActionScript 3 to JavaScript? Additionally, how can one convert a ByteArray back into an image using JavaScript? ...

What is the best way to use axios in Vue 3 to update variables?

Is there a way to dynamically update the example variable {{user.email}} when the user makes changes to the input field? I've already tested the backend functionality using Postman and everything is working fine. On the frontend, I'm utilizing V ...