Encode base64 Java image

1

I'm trying to convert an image to a String base64 (I need to send it via POST ) and I can not get it. I use the following instruction:

String imgDS = DatatypeConverter.printBase64Binary(Files.readAllBytes(Paths.get(".\imagen.png")));

It is a large image with high resolution (2.2MB), therefore it generates a very large String (2 million characters).

When I clean, I look at the variables and a strange thing happens. the variable "stringNormal" if it has its value next to it, but the variable imgDS does not. But when clicking on it, it appears below its value.

This variable I need to send it through a POST , but when sending it the server receives it empty.

Does anyone know what happens?

Thanks

    
asked by David 20.04.2017 в 18:18
source

1 answer

1

You can try something like this:

import sun.misc.BASE64Encoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

StringBuilder path = new StringBuilder();
path.append("ruta de tu imagen");
String imageBase64 = null;
byte[] base64EncodedImage= null;
BASE64Encoder encoder = new BASE64Encoder();
try {
    base64EncodedImage = loadImage64(path.toString());
    if(base64EncodedImage != null){
        imageBase64 = encoder.encodeBuffer(base64EncodedImage);
        if(imageBase64 != null && !imageBase64.trim.equals("")){
            //La envías a tu servidor
        }
    }
}catch(Exception e){

}

Here you load it and convert it to base64, doing their respective validations

public byte[] loadImage64(String url)throws Exception{

File file= new File(url.toString());
if(file.exists()){
    int lenght = (int)file.length();
    BufferedInputStream reader = new BufferedInputStream(new FileInputStream(file));
    byte[] bytes = new byte[lenght];
    reader.read(bytes, 0, lenght);
    reader.close();
    return bytes;
}else{
    log.info("Recurso no encontrado");
    return null;
}

}

Verify that the file exists and load it in a byte []

    
answered by 20.04.2017 в 18:39