js检查图像是否被截断/损坏的数据 [英] js check if an image truncated/corrupted data
问题描述
我正在寻找如何检测图像数据被截断\损坏.例如此图片:
I'm looking for how to detect an image data is truncated\corrupted. For example this picture:
数据图像不完整(在IE上更明显,并且在firefox控制台中显示为警告),但是未触发img.onerror,并且img.completed为真.
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.
演示: 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))
JPEG必须从字节FF D8开始,以FF D9 结尾,因此我们检查创建的数组缓冲区的最后两个元素是否为255和217.请参见 live例子.
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));
我们可以对PNG使用类似的检查(实时示例),该检查
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];
这篇关于js检查图像是否被截断/损坏的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!