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?
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?
Share Improve this question asked Jan 9, 2012 at 21:45 NRafNRaf 7,54914 gold badges56 silver badges92 bronze badges 2- 1 See: stackoverflow.com/questions/469695/decode-base64-data-in-java – Simon Sarris Commented Jan 9, 2012 at 21:51
- possible duplicate of Uploading 'canvas' image data to the server – user177800 Commented Jan 9, 2012 at 21:53
4 Answers
Reset to default 7You need to remove the data:image/png;base64,
part and base 64 decode the rest.
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
}
}
}
Once you Base64-decode the string, you will have the binary image, in the form of a PNG file. See this SO question for details on how to decode a base64 string into bytes.
You have to replace space with + if your base64Image have space char, then you have to remove data:image/png;base64, from the beginning of the base64Image. Unless you replace space char, you can't get correct Image. then you can use Base64 decode
yourBase64String = yourBase64String.replace(' ', '+');
yourBase64String = yourBase64String.substring(22);