Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending the contents of a canvas to a Java server and saving it as an image

Okay, basically I've developed a simple image upload system. The user selects a local image (using the HTML5 File / FileReader API) and has the ability to crop it before confirming the result.

The final result is viewed in a canvas so to send it to the server I'm using toDataURL. The backend server is a NodeJS server which then needs to make a REST call to a Java server which will create an image file from the data and save it to disk.

The results of toDataURL are in the form: data:image/png;base64, ENCODED DATA.

What would I need on the Java server to convert the string into it's proper binary representation?

like image 648
NRaf Avatar asked Jan 09 '12 21:01

NRaf


People also ask

How do you save an HTML5 canvas as an image on a server?

Saving HTML canvas as an image is pretty easy, it can be done by just right-clicking on the canvas and save it as an image.

How do I save my data on canvas?

To save a new Canvas document:Choose File | Save As. In the Save As dialog box, select a location to store the document and type a file name. Click Save to store the document on disk.

How do I convert a file to canvas?

toDataURL( ) ; / / This method saves graphics in png document. getElementById('cimg'). src = imgurl; // This will set img src to dataurl(png) so that it can be saved as image. In this way, we can save canvas data to file in HTML5.


2 Answers

You need to remove the data:image/png;base64, part and base 64 decode the rest.

like image 183
copy Avatar answered Oct 01 '22 10:10

copy


import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import javax.imageio.ImageIO;
import javax.xml.bind.DatatypeConverter;

public class test {
    public static void main (String[] args){
     try{
            // remove data:image/png;base64, and then take rest sting
            String img64 = "64 base image data here";
        byte[] decodedBytes = DatatypeConverter.parseBase64Binary(img64 );
        BufferedImage bfi = ImageIO.read(new ByteArrayInputStream(decodedBytes));    
        File outputfile = new File("saved.png");
        ImageIO.write(bfi , "png", outputfile);
        bfi.flush();
     }catch(Exception e)
         {  
          //Implement exception code    
     }

    }
}
like image 20
M.Sanad Avatar answered Oct 01 '22 10:10

M.Sanad