I'm looking for how to detect an image data is truncated\corrupted. For example this picture:
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.
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With