Siniša
Siniša

Reputation: 3158

Detect is jpg image is properly loaded

I am developing a webapp (HTML5, pure JavaScript, no JQuery), and it's a image gallery.

Images (thumbs) are loaded using Image object, and then drawn into a Canvas2D. It all works great except I have noticed that sometimes on iPhone 6+ (iOS 8.1, Safari) some of thumbs may have black thick margin at the bottom.

Image fires no 'onerror' event, but always 'onload' event.

When I print out loaded image size in console, upon 'onload' event is called, it is always expected 512x512 size (all thumbs are in that size), regardless if black margin appeared or not. Image is not shifted up, it basically has missing pixels at the bottom, replaced with black pixels, as if JPG loading was interrupted.

There are about 40 thumbs in the gallery, and this issue manifests always to same 3 thumbs, but not every time I load gallery in iOS Safari. Rather there's about 3 out of 10 chance it will appear.

This never happens on Android devices, or Windows/OSX desktops.

Code which sets image object for loading:

this.itms[i].img.onload = onImageLoad;
this.itms[i].img.onerror = onImageErr;
this.itms[i].img.src = path_to_jpg_file;

Where 'this' is gallery object, 'itms' is array of gallery items, 'img' is actual Image object.

When 'onload' event is fired, following code will draw image into a canvas:

this._ctx.clearRect(0,0,this._ctx.canvas.width,this._ctx.canvas.height);
this._ctx.drawImage(this.img,0,0,this.img.width,this.img.height,0,0,this._ctx.canvas.width,this._ctx.canvas.height);
this.dtext(this.img.width + "x" + this.img.height);

Where 'this' is gallery item object, '_ctx' is canvas2D context pointer and 'dtext' is a function that will draw debug text into canvas2D context. All thumbs are 512x512 on server, and each time image is loaded, it always shows 512x512 size.

Image object is never added to document body, rather it is drawn into a canvas2D which is in document body. Reason for this is that there will be some composition later on done in canvas (some visual effects).

I can't just scan for black pixel rows at the bottom since there are some thumbs that do have lots of black.

Has anyone encountered similar issue? Any ideas how to detect if loaded image had some invalid pixels decoded?

Upvotes: 0

Views: 359

Answers (1)

MasterMohsin
MasterMohsin

Reputation: 168

You can use following script

var image = new Image();

var imageSource = "http://website.com/image.jpg";

// image load event.
image.onload = function() {
   alert("image loaded");
};

// Now set the source.
image.src = imageSource;

Upvotes: 1

Related Questions