Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML5

Uncaught IndexSizeError: Failed to execute ‘getImageData’ on ‘CanvasRenderingContext2D’: The source width is 0.

4 Oct 2016CPOL1 min read 16.6K  
We will discuss a problem that I recently came across while working with images in coding.

Introduction

In this post, we will discuss a problem which I recently came across while working with images in coding.

Background

The job was to take one image from the file upload control and then compress it using canvas before uploading it to the server. I used a plug in, but let’s not go into that. We will directly come to the point where this problem can happen.

Problem

So, the line that we are talking about is like below:

JavaScript
var canvas = canvas.getContext('2d')
                   .getImageData(0, 0, imgWidth, imgHeight);

We are sending image width and height to getImageData. However, if you analyze the error message, it says that width is 0.

Solution

With further research on developer console while debugging, I found that the width and height are actually populated in some other properties named as naturalWidth and naturalHeight.
Therefore, we can write the code like below:

JavaScript
var imgWidth = image.width || image.naturalWidth;
var imgHeight = image.height || image.naturalHeight;

var canvas = canvas.getContext('2d')
                   .getImageData(0, 0, imgWidth, imgHeight);

Now your program should work as expected without errors.

More on naturalHeight and naturalWidth from MDN

HTMLImageElement.naturalHeight (Read only)
Returns an unsigned long representing the intrinsic height of the image in CSS pixels, if it is available; else, it shows 0.
HTMLImageElement.naturalWidth (Read only)
Returns an unsigned long representing the intrinsic width of the image in CSS pixels, if it is available; otherwise, it will show 0.

Feedback

If you like this blog, feel free to share it in your circle and save someone’s time. Please comment below, if you have any inputs for me.

Thanks for reading. Have a nice day ahead.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)