<!DOCTYPE html>
JPEG image RGB pixels should render without color corruption and in strict<br>
order, regardless of the underlying machine pixel buffer endianess.<br><br>

<img src="resources/rgb-jpeg-red.jpg"   onload="test(this, [255,0,0,255])">
<img src="resources/rgb-jpeg-green.jpg" onload="test(this, [0,255,0,255])">
<img src="resources/rgb-jpeg-blue.jpg"  onload="test(this, [0,0,255,255])">

<pre id="log">PASS</pre>

<script>
if (window.testRunner) {
    window.testRunner.waitUntilDone();
    window.testRunner.dumpAsText();
}

function log(message)
{
    document.getElementById("log").textContent += '\n' + message;
}

function averagePixelComponents(data, size)
{
    var r = 0, g = 0, b = 0, a = 0;
    for (var i = 0, total = size * 4; i < total; i += 4) {
        r += data[i + 0];
        g += data[i + 1];
        b += data[i + 2];
        a += data[i + 3];
    }

    return [r / size, g / size, b / size, a / size];
}

function averagePixelShouldBe(pixel, expect, tolerance)
{
    var delta = 0;
    pixel.forEach(function(component, i) {
        delta = Math.max(Math.abs(pixel[i] - expect[i]), delta);
    });

    if (delta > tolerance)
       log('FAIL: [' + pixel + '] expected [' + expect + '] +/- ' + tolerance);
}

function testImage(image, expect)
{
    // Create a canvas, load the given image in it.
    var canvas = document.createElement("canvas");
    canvas.width = canvas.height = 64;
    var context = canvas.getContext("2d");
    context.drawImage(image, 0, 0);

    // Compare the canvas pixel component averages.
    var pixels = context.getImageData(0, 0, 64, 64).data;
    var result = averagePixelComponents(pixels, 64 * 64);

    var pixelTolerance = 3;
    averagePixelShouldBe(result, expect, pixelTolerance);
}

function test(image, expect)
{
    try {
        loadedImages = window.loadedImages || 0;
        testImage(image, expect);
        if (++loadedImages < 3)
            return;
    } catch (e) {
        log('FAIL: ' + e.message);
    }

    if (window.testRunner)
        window.testRunner.notifyDone();
}
</script>
