I am trying to crop/resize user profile image using jquery plugin namely crop.js which sends user image as base64 via ajax to my controller as
$.ajax({ type: "post", dataType: "json", url: "${g.createLink(controller: 'personalDetail', action:'uploadUserImage')}", data: { avatar: canvas.toDataURL() } });
but I unable to decode this base64
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPAAAADwCAYAAAA+VemSAAAgAEl...=='
string as Image,Can you guys guide me how can I save my base64 string as image on my server?.
After converting image, you can download this as png file / picture. This tool helps you to convert your Base64 String to image with Ease. Base64 encoding tool supports loading the Base64 text File to transform to Image. Click on the Upload File button and select File.
In the server, do something like this:
Suppose
String data = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPAAAADwCAYAAAA+VemSAAAgAEl...=='
Then:
String base64Image = data.split(",")[1]; byte[] imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(base64Image);
Then you can do whatever you like with the bytes like:
BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageBytes));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With