0

I have a image data from which I need to remove the following substring

data:image/jpeg;base64,

from the string

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD......

data:image/png;base64......
data:image/;base64

and then I am thinking of doing something like the following

   imageData = imageData.replace("regex", "");
   return Base64.decodeBase64(imageData.getBytes());

I want to know the regex first and also want to know whether calling

    imageData.getBytes()

will work out or not...

Saurabh Kumar
  • 16,353
  • 49
  • 133
  • 212

2 Answers2

7
  1. .replace(regex,repl) treats regex as "literal" (doesn't allow to use "^" to denote beginning of line, etc) - try .replaceFirst(regex,repl) instead
  2. as discussed here - try other Base64-decoders (which might better suit Your needs, the one below may have issues above 64KB of string length)

Aside from validation/handling - should end up with something like this:

String imageData = "data:image/jpeg;base64,SGVsbG8sIHdvcmxkIQ==";
imageData = imageData.replaceFirst("^data:image/[^;]*;base64,?","");
byte[] bytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(imageData);
System.out.println(new String(bytes));

Output:

Hello, world!
Community
  • 1
  • 1
Vlad
  • 1,157
  • 8
  • 15
0

The simplest way I found is to split it at the comma and then save the right side of the resulted array, to demonstrate:

if (imageData.contains(",")) {
    imageData = imageData.split(",")[1];
}

This splits the base at the comma (which returns an array) and saves the second item (what was after comma) back to the variable.*

At this point we have the base64 without the metadata.

Now, if you want to save the base64 into a byte array we can simply do so with the following code:

byte[] byteArr = Base64.getDecoder().decode(imageData);

*Base64 should not have any other commas in it so do not worry about it splitting further (but in case you want to use .split() elsewhere you can always pass a second parameter that will limit the number of resulting strings after the split, say if you want it to split only at the first comma then it would look like .split(",", 2);

Vahe Aslanyan
  • 76
  • 1
  • 4