omega
omega

Reputation: 43843

How to get a dataurl base 64 encoding from a canvas but only for a sub image?

I have a canvas, and I want to get a base64 encoding from it to send to server, which I can do with .toDataURL(). But the problem is I don't want to send the whole image, I want to send a portion of it. I then have

.getImageData(x, y, w, h) to get the image data of the portion. But now how can I get the data url of this to send to the server?

Does anyone know?

Thanks

Upvotes: 1

Views: 280

Answers (2)

Blindman67
Blindman67

Reputation: 54026

Just create a temp canvas and copy the pixels to the canvas then get the data URL of that canvas

// context is the context from which to copy
// x,y,w,h is the sub area to copy ar data URL
function getDataURLSubImage(context,x,y,w,h){
    var can = document.createElement("canvas");
    can.width = w;
    can.height = h;
    var ctx = can.getContext("2d");
    ctx.drawImage(context.canvas,-x,-y);
    return can.toDataURL();
}

Or if you only have imageData you can do the following but it is less efficient than the above method.

function imageDataToDataURL(imageData){
    var can = document.createElement("canvas");
    can.width = imageData.width;
    can.height = imageData.height;
    var ctx = can.getContext("2d");
    ctx.putImageData(imageData,0,0);
    return can.toDataURL();
}

Upvotes: 2

Sriram Rajendran
Sriram Rajendran

Reputation: 56

In javascript, the dataURL can be sent in JSON format. $scope.canvasObject = { "screenName" : 'testName', "screenObject" : JSON.stringify(canvas.toDataURL()) };

In serverside, this will be received in byte array format.

    byte[] bytes = null;
    File file = null;
    BufferedImage bfi = null;
    try {
        if (entity != null && entity.getScreenObject() != null) {
            bytes = DatatypeConverter
                    .parseBase64Binary(entity.getScreenObject().replaceAll("data:image/png;base64,", ""));
            file = new File(entity.getScreenName() + System.currentTimeMillis() + ".png");
            bfi = ImageIO.read(new ByteArrayInputStream(bytes));
            ImageIO.write(bfi, "png", file);
            bfi.flush();
        }
    } catch (Exception e) {
        // handle exception
    }

This saves the image in server.

Upvotes: 0

Related Questions