When an image is loaded, the getImageData function may return some zero values

I am currently working on a task that involves loading a PNG image and checking to see if it is fully opaque, meaning the alpha channel has near 100% coverage across the entire image. To achieve this, I am using a canvas and 2D Context to extract pixel data and iterate through it to inspect the alpha values.

However, I encountered a puzzling issue where certain areas of the image have pixel values of zeros (RGBA = [0000]), which is unexpected.

Browser in focus: chrome 50.0.2661.87

Below is my code snippet embedded within a ThreeJS environment:

var imageData = zipHandler.zip.file(src); // binary image data

var texture = new THREE.Texture();

var img = new Image();
img.addEventListener( 'load', function ( event ) {

    texture.imageHasTransparency = false; // extending THREEJS Texture with a flag

    if (img.src.substring(imgSrc.length-4).toLowerCase().indexOf("png") > -1 
        || img.src.substring(0, 15).toLowerCase().indexOf("image/png") > -1) {

        var canvas = document.createElement('canvas');
        var context = canvas.getContext('2d');
        context.drawImage(img, 0, 0, img.width, img.height );
        var pixDataContainer = context.getImageData(0, 0, img.width, img.height);
        var pixData = pixDataContainer.data;

        // scanning for pixels with alpha < 250
        for (var pix = 0, pixDataLen = pixData.length; pix < pixDataLen; pix += 4) {
            if (pixData[pix+3] < 250) {
                texture.imageHasTransparency = true;
                break;
            }
        }
    }

    texture.image = img;
    texture.needsUpdate = true;
    this.removeEventListener('load', arguments.callee, false);

}, false );

var fileExtension = src.substr(src.lastIndexOf(".") + 1);
img.src = "data:image/"+fileExtension+";base64,"+ btoa(imageData.asBinary());

The sequence of operations is crucial: initializing a new Image(), defining the onload function, and setting the source afterwards.

Answer №1

Issue resolved. It was discovered that the image exceeded the canvas size, causing only a portion of it to be displayed when using context.drawImage(). By adjusting the canvas dimensions based on the image size, the problem was rectified and the functionality restored:

// ...
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
canvas.width = img.width; // !!!!!
canvas.height = img.height; // !!!!
context.drawImage(img, 0, 0, img.width, img.height );
var pixDataContainer = context.getImageData(0, 0, img.width, img.height);
var pixData = pixDataContainer.data;
// ...

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

Include chosen select option in Jquery form submission

Facing some challenges with a section of my code. Essentially, new elements are dynamically added to the page using .html() and ajax response. You can see an example of the added elements in the code. Since the elements were inserted into the page using . ...

The ChromeDriver on Selenium is not compatible with Google Chrome, causing compatibility issues

I am currently using Google Chrome version 112.0.5615.138 (Official Build) (64-bit) with a Web driver version of 112.0.5615.49. Upon executing the code, the following error was encountered: SLF4J: No SLF4J providers were found. SLF4J: Defaulting to no-ope ...

Tips on connecting the endpoints of two parallel quadratic Bezier curves that both begin with a MoveTo command

I am currently working on creating a Sankey Diagram from scratch using VueJS and SVG. I have encountered challenges in closing the paths of two parallel quadratic Bezier curve paths from nodes to nodes. For instance, after some additional calculations, I ...

importing files from Uploadcare using ngCordova MediaFile

I am facing an issue while attempting to upload a sound file from ngCordova's $cordovaCapture service to UploadCare. The `uploadcare.fileFrom('object')` function is failing with an 'upload' error even though I have set the public k ...

Utilizing directive scope variables to generate dynamic templates

Looking for a solution to dynamically render forms with various controls based on a specific Type value specified in a JSON object. The form will be created based on user input, so the necessary question types may vary. While we will define the types, they ...

Guide to customizing the sort arrow colors of b-table in Bootstrap 4 within Nuxt framework

https://i.sstatic.net/axVNu.png Using nuxt and bootstrap, I've noticed that the default sorting arrows in the table are too dark for my background. Is there a way to change the color of these sorting arrows? <b-table show-empty small ...

Show the chosen item from a dropdown menu using Bootstrap

Here is the HTML code that I am working with: <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="h ...

Building a hybrid application in Angular using UpgradeModule to manage controllers

I am currently in the process of upgrading a large AngularJS application using UpgradeModule to enable running AngularJS and Angular 6 simultaneously without going through the preparation phase, which typically involves following the AngularJS style guide. ...

What is the best way to iterate through an array in Vue using only half the number of iterations as the total number of items?

My data is stored in an array: [ { type: select, options: [foo, bar], label: foo, required: true }, { type: text, options: [], label: bar, required: false }, { type: checkbox, options: [], lab ...

How can I retrieve the height of a div element once its content has been altered in

I am currently updating the content of a div dynamically and I need to immediately get its new height after the change. var text='Bla-bla-bla Bla-bla-bla Bla-bla-bla Bla-bla-bla Bla-bla-bla Bla-bla-bla Bla-bla-bla Bla-bla-bla Bla-bla-bla Bla-bla-bla ...

How to access a function defined within the jQuery ready function externally

My ASPX page content:- <script src="js/jquery-1.4.2.js" type="text/javascript"></script> <script src="js/jquery-ui-1.8.2.custom.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready ...

What is the reason for the request body being undefined?

I have a JavaScript file named index.js that contains: const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const db = require('./db'); const movieRouter = re ...

Using Vue.js watchers can sometimes cause an endless loop

I'm working on a unique aspect ratio calculator. How can I ensure my code doesn't get stuck in an endless loop when dealing with 4 variables that are dependent on each other? To address this, I implemented 4 watchers, each monitoring a specific ...

Fetching locales asynchronously in nuxt.js using i18n and axios: A step-by-step guide

I am facing an issue with getting the location asynchronously. Whenever I try to implement my code, it results in a "Maximum call stack size exceeded" error. How can I resolve this issue? Previously, I attempted to retrieve the location by using the axios ...

Is there a way to show all the items within a specific folder simply by clicking on the folder's name?

When a folder name is clicked, I would like to display all images from that particular folder. Currently, the code displays the list of folder structure and images separately, but my goal is to show the images only when the folder name is clicked. List of ...

JavaScript ECMAScript 6 - WARNING: "Decorators can only be applied to a class when exporting"

In ECMAScript 6, I am attempting to export a function so that I can import it and utilize it in other files for the sake of writing DRY code. However, an error message is appearing: You can only use decorators on an export when exporting a class (16:0) ...

Determine the number of elements located inside a designated slot

Take a look at this Vue component code: <template> <!-- Carousel --> <div class="carousel-container"> <div ref="carousel" class="carousel> <slot></slot> </div> </div&g ...

Using JavaScript, aim for a specific element by its anchor headline

I'm looking to make some changes to my navigation menu, specifically hiding the home menu item unless the mobile navigation menu is toggled. Is there a way for me to target the "home" anchor title and apply the active class to it when toggled, similar ...

How to display a name in an iframe using React

When I retrieve the movie name in React, it appears correctly as {movie.name} / {movie.enname} ({years}) . However, when I try to display this name within an iframe window at https://example.com/movie/{movie.name}, it does not show up properly. Here is th ...

Encountered an issue while attempting to integrate Nebular into my Angular application

As a newcomer to Angular, I decided to try installing Nebular using the command ng add @nebular/theme. However, I encountered an error in the process. Upon entering the command into my terminal, the following error message appeared: ? Which Nebular theme ...