Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
658 views
in Technique[技术] by (71.8m points)

javascript - js check if an image truncated/corrupted data

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

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

1 Reply

0 votes
by (71.8m points)

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];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...