16

I have just tried a sample code form net it shows a warning as follows

SimpleConvertImage.java:7: warning:com.sun.org.apache.xerces.internal.impl.dv.util.Base64 is internal proprietary API and may be removed in a future release import com.sun.org.apache.xerces.internal.impl.dv.util.Base64; ^

SimpleConvertImage.java:16: warning: com.sun.org.apache.xerces.internal.impl.dv.util. Base64 is internal proprietary API and may be removed in a future release String base64String=Base64.encode(baos.toByteArray()); ^

SimpleConvertImage.java:19: warning: com.sun.org.apache.xerces.internal.impl.dv.util .Base64 is internal proprietary API and may be removed in a future release byte[] bytearray =Base64.decode(base64String); ^

the code is the below one

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64; 
public class SimpleConvertImage {
    public static void main(String[] args) throws IOException{
        String dirName="/root/Desktop";
        ByteArrayOutputStream baos=new ByteArrayOutputStream(1000);
        BufferedImage img=ImageIO.read(new File(dirName,"Screenshot.png"));
        ImageIO.write(img, "png", baos);
        baos.flush();

        String base64String=Base64.encode(baos.toByteArray());
        baos.close();

        byte[] bytearray =Base64.decode(base64String);

        BufferedImage imag=ImageIO.read(new ByteArrayInputStream(bytearray));
        ImageIO.write(imag, "png", new File(dirName,"snap3.png"));
    }
}

ambrosia1993
  • 245
  • 2
  • 5
  • 13
  • 1
    The warning says it all: You're using a class that Xerces is telling you not to use, because it's internal and proprietary and may be removed and probably smells bad too. Luckily, there are other base64 encoding/decoding options available: http://stackoverflow.com/questions/469695/decode-base64-data-in-java – Sneftel Feb 20 '14 at 10:18
  • 1
    And in Java 8, it finally has official support http://stackoverflow.com/a/15646871/637889 – andyb Feb 20 '14 at 11:57

2 Answers2

26

Don't use internal com.sun.* packages. If you are on v6 or greater you can use DatatypeConverter. Your code would look like:

String base64String = DatatypeConverter.printBase64Binary(baos.toByteArray());
byte[] bytearray = DatatypeConverter.parseBase64Binary(base64String);
mikea
  • 6,537
  • 19
  • 36
18

You can also use: java.util.Base64 Added to Java 1.8

String encryptedValue = new String(Base64.getEncoder().encode(bytesToEncode));
byte[] decodedValue = Base64.getDecoder().decode(encryptedDataString);
Wolfgang Fahl
  • 15,016
  • 11
  • 93
  • 186
Mayank
  • 981
  • 7
  • 9