Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert base64 string to image

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?.

like image 274
Abs Avatar asked Jun 01 '14 12:06

Abs


People also ask

How do I decode Base64 image data?

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.


2 Answers

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)); 
like image 128
user711189 Avatar answered Oct 14 '22 14:10

user711189


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.

like image 42
Joshua Moore Avatar answered Oct 14 '22 15:10

Joshua Moore