简体   繁体   中英

Javascript Get pixel data of image

I need to load a png file from my computer and loop through each pixel value. I tried canvas, but it breaks with the cross-domain stuff I dont understand...

var img = new Image(); 
img.src = "map.png";

var canvas = document.getElementById("secondaryCanvas");
var ctx = canvas.getContext("2d");

ctx.drawImage(img, 0, 0, 30, 30);

console.log(ctx.getImageData(0,0,1,1));

...Sometimes it works, sometimes it doesnt?... Im absolutely lost

You can not read the pixel data if the page is being load directly from the file system. You must load the page from a web server. Install apache and load it from localhost

About the fact that it sometimes "work" it depends on whether the image has been draw in the canvas when you call getImageData.

if the image has not been loaded you can call getImageData because you are not reading the image data but the blank canvas.

if you call the getImageData inside the image onload event the code will always fail

var img = new Image(); 
img.onload = function() {
    console.log(this)
    var canvas = document.getElementById("secondaryCanvas");
    var ctx = canvas.getContext("2d");

    ctx.drawImage(img, 0, 0);

    console.log(ctx.getImageData(100,100,1,1));
}
img.src = "map.png";

This is a quick (althopugh not clean) example that I made on the bus just because I couldn't believe that nobody answered with this hack

If you want to test it save it as index.html and open it with chrome

TLDR; load file as base64 then use it as src for the image

<script>

    async function toBase64(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = () => resolve(reader.result);
            reader.onerror = error => reject(error);
        });
    }

    async function reset() {
        const input = document.querySelector('input');
        console.log(input.files)

        const base64 = await toBase64(input.files[0]);
        console.log(base64)

        const src = base64;

        var img = new Image();
        img.onload = function () {
            console.log(this)
            var canvas = document.getElementById("secondaryCanvas");
            var ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0);
            console.log(ctx.getImageData(100, 100, 1, 1));
        }
        img.src = src;
    }
</script>
<input type="file" id="input" onchange="reset()" />
<canvas id="secondaryCanvas"></canvas>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM