Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm looking for how to detect an image data is truncatedcorrupted. For example this picture: enter image description here

the data image is not complete (It's more tangible on IE, and its noted as warning in firefox console), but img.onerror not fired, and img.completed is true.

demo: https://jsfiddle.net/7dd0ybb4/

var img = document.getElementById('MyPicture');

img.onerror = () => alert('error img');  
img.onload = () =>  console.log(img.complete); //true

img.src = "https://i.stack.imgur.com/nGkok.jpg";

I want a way to know that. if an image have invalid data.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
643 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can decode an image to an array of bytes:

var src = 'here comes your base64 data'
var imageData = Uint8Array.from(atob(src.replace('data:image/jpeg;base64,', '')), c => c.charCodeAt(0))

JPEGs must start with the bytes FF D8 and end with FF D9, so we check if last two elements of the created array buffer is 255 and 217. See live example.

var imageCorrupted = ((imageData[imageData.length - 1] === 217) && (imageData[imageData.length - 2] === 255));

We can use a similar check for PNGs (live example), which end with an IEND chunk containing this sequence of bytes:

// in hex: 00 00 00 00 49 45 4e 44 ae 42 60 82
var sequence = [0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...