How to convert an image as a string to a PNG file

I am using a jQuery plugin called wPaint so that users can draw their own image. I send the received image as a string to the server as a string that starts with

data: images / PNG; base64,

I tried the two approaches below, but with both approaches I cannot save 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 recorded, but does not show the image. However, when I delete the file extension, I get a string that was sent to the server (i.e., Everything that 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"));

BufferedImage bImageFromConvert is null, so I get an exception (IllegalArgumentException) when creating the file.

Base64 apache commons 1.2.

-, ?

+5
2

, .

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

,

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

:

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();
    }
+5

, data:image/png'base64 Base64? , Base64 .

, ... .

0

All Articles