javaajaximagegrailsbase64

Convert Base64 string to image


I am trying to crop/resize user profile images using the jQuery plugin crop.js which sends user images as Base64 via Ajax to my controller:

$.ajax({
        type: "post",
        dataType: "json",
        url: "${g.createLink(controller: 'personalDetail', action:'uploadUserImage')}",
        data: { avatar: canvas.toDataURL() }
        });

But I'm unable to decode this Base64 string to an image:

'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPAAAADwCAYAAAA+VemSAAAgAEl...=='

How can I save the Base64 string as an image on my server?


Solution

  • This assumes a few things, that you know what the output file name will be and that your data comes as a string. I'm sure you can modify the following to meet your needs:

    // Needed Imports
    import java.io.ByteArrayInputStream;
    import sun.misc.BASE64Decoder;
    
    
    def sourceData = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPAAAADwCAYAAAA+VemSAAAgAEl...==';
    
    // tokenize the data
    def parts = sourceData.tokenize(",");
    def imageString = parts[1];
    
    // create a buffered image
    BufferedImage image = null;
    byte[] imageByte;
    
    BASE64Decoder decoder = new BASE64Decoder();
    imageByte = decoder.decodeBuffer(imageString);
    ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
    image = ImageIO.read(bis);
    bis.close();
    
    // write the image to a file
    File outputfile = new File("image.png");
    ImageIO.write(image, "png", outputfile);
    

    Please note, this is just an example of what parts are involved. I haven't optimized this code at all and it's written off the top of my head.