upload image with ajax from camera using p5.js

908 Views Asked by At

I am using p5.js and its video capture capability to use the camera. I want to use ajax to take some of those images and upload them to a server. I dont know how to convert a p5.js Image object into a format that I can use to send over the wire with ajax. The error I get is:

Uncaught TypeError: Illegal invocation

Can someone please help me with this, here is the code:

function process_image(img) {
    var url = "http://random.com/process_image";
    $.ajax({
        url: url,
        type: " POST ",
        crossDomain: true,
        dataType: " json ",
        data: {
            image: img
        },

        // Work with the response
        success: function (response) {
            console.log(response); // server response
        },
        error: function (response) {
            console.log(response);
        }
    });
}

function setup() {
    createCanvas(900, 900);
    capture = createCapture(VIDEO);
    capture.size(320, 240);
    //capture.hide();
}

function draw() {
    background(255);
    image(capture, 0, 0, 320, 240);
    filter('INVERT');
    process_image(capture);

}
2

There are 2 best solutions below

4
On

You have a missing quote in var url = "http://random.com/process_image;

function process_image(img)
{
    var url = "http://random.com/process_image";

    $.ajax(
    {
        url: url,
        type: "POST",
        crossDomain: true,
        dataType: "json",
        data:
        {
            image: img
        },
        // Work with the response
        success: function(response)
        {
            console.log(response); // server response
        },
        error: function(response)
        {
            console.log(response);
        }
    });
}

function setup()
{
    createCanvas(900, 900);
    capture = createCapture(VIDEO);
    capture.size(320, 240);
    //capture.hide();
}

function draw()
{
    background(255);
    image(capture, 0, 0, 320, 240);
    filter('INVERT');
    process_image(capture);
}
2
On

Like you've discovered, the problem is that capture is a P5.Image, which isn't something that can be simply uploaded to a server. It's not an image file. It's a data structure specific to P5.js that can render images in P5.js.

So, you need to convert your P5.Image into a file that you can then upload to a server. You might check out the P5.Image.save() function which saves the P5.Image as a file onto the client's file system.

You might also explore creating an in-memory version of the P5.Image. You'd start by getting the pixel data from the image using the P5.Image.get() function, then you'd convert that data into whatever format you want to upload.