How do i convert a image as a string to PNG file

java, struts2

Solution

Initially I had sent the data to the server using the following code.

    $.ajax({
        url : '/campaign/holiImageUpload.action',
        type : 'POST',
        data : "image=" + $("#wPaint2").wPaint("image")
        success :function(data){
        }
    });

Now i'm sending the data to the server using the following code

var imgData = $("#wPaint2").wPaint("image");
    $.ajax({
        url : '/campaign/holiImageUpload.action',
        type : 'POST',
        data : {image : imgData},
        success :function(data){
        }
    });

In the server side this is the final code :

String imageData = parameterParser.getStringParameter("image", "");

    try {
        imageData = imageData.substring(22);
        byte[] imgByteArray = Base64.decodeBase64(imageData.getBytes());
        InputStream in = new ByteArrayInputStream(imgByteArray);
        BufferedImage bufferedImage = ImageIO.read(in);
        ImageIO.write(bufferedImage, "png", new File("/home/arvind/Desktop/test.png"));
    catch(Exception ex){
        ex.printStrackTrace();
    }

Problem

I'm using a jQuery plugin called wPaint to allow users to draw their own image. I send the resulting image as a string to the server as a string which begins with data:image/png;base64, I tried the two approaches below but with both the approaches i'm not able to store the image. Approach 1 ``` String imageData = parameterParser.getStringParameter("image", ""); byte[] imgByteArray = Base64.decodeBase64(imageData.getBytes()); FileOutputStream fileOutputStream = new FileOutputStream("/home/arvind/Desktop/test.png"); fileOutputStream.write(imgByteArray); fileOutputStream.close(); ``` In this case the file is written but doesn't show the image. However, when i remove the file extension i get the string that was sent to the server (i.e. whatever is in imageData). Approach 2 ``` String imageData = parameterParser.getStringParameter("image", ""); byte[] imgByteArray = Base64.decodeBase64(imageData.getBytes()); InputStream in = new ByteArrayInputStream(imgByteArray); BufferedImage bImageFromConvert = ImageIO.read(in); ImageIO.write(bImageFromConvert, "png", new File("/home/arvind/Desktop/test.png")); ``` The BufferedImage bImageFromConvert is null so I get an exception (IllegalArgumentException) when the file is created. The Base64 class is from the apache commons codec library and is version 1.2. Is there something I'm doing wrong?

Original source