How to convert a byte [] from an image to a jpeg image to load in html?

3

In the html (jsp) of register I have a field that the user registers his photo getting the tag img with the following result.

<img src="data:image/png;Base64,/9/0kmkdmkewnsjdncijndcjdxncdjcdscjnccc/ccnkjdncnsjnidckcmokcmoskcmkosmcokmdscjncjncjcsnckdjncojnscjncdjnckmkdmcokscmksmdckcmsokcmnjncjemncmokkjcmdjsdccmslckjplqmkmokswkmxokamlamklmockmclmdkcmlodkcmokcmkmcokmsomcksmcsfhhgfrfcghjkuytredfhjolkjhsSWswjshuhuwhuhyhuimcoskcmkmsckmkmkcmc"
/>

I am converting the excerpt Base64, to a byte [] with sun.misc.BASE64Decoder, as below:

import Decoder.BASE64Decoder;
import Decoder.BASE64Encoder;

/**
* @author Tiago Ferezin
* 
* para o tratamento da imagem
*
*/
public class Imagem {

public static byte[] convertBase64StringToByteArray(String imagem){
    byte[] retorno = null;

    try {
        BASE64Decoder decoder = new BASE64Decoder();
        retorno = decoder.decodeBuffer(imagem);
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }

    return retorno;

}

public static String convertByteArrayToBase64String(byte[] imagem){
    String retorno="";

    try {
        BASE64Encoder encoder = new BASE64Encoder();
        retorno = encoder.encode(imagem);
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }

    return retorno;
}

}

And save the generated byte to the bank.

First I wanted to know how before writing to the bank, get the image type (png, ttf, jpg, psd) and convert it to JPEG , and then generate an array of it and write to the bank?

Second, I would like to know how to convert this byte [] stored in the database to a String data:image/jpeg;Base64,{byte[]} to put in a img tag on another JSP page?

    
asked by anonymous 11.03.2016 / 19:11

1 answer

2

To read an image, you can use the ImageIO class. . The read () method receives an InputStream. I do not know the overload that directly receives a URL (does it recognize the "protocol" date:?), But it is quite easy to convert to byte [] using a ByteArrayInputStream . The source format should be detected automatically.

To convert to another format, just get the image returned by read () and call ImageIO.write () passing the desired destination format as parameter. The output will be written to an OutputStream, so you can use a ByteArrayOutputStream to get the generated bytes.

To generate the String and put it on the page, I ask if it would not suffice to simply concatenate "data: image / jpeg; Base64," + Base64.Encoder.encodeToString (bytes)? If there is no surprise in the format (or "protocol") date :, it should work.

Note: If you are using Java 8, there is already an official Base64 , out of the package sun.misc, which runs the risk of being removed (or made inaccessible) in future versions of Java.

    
14.03.2016 / 15:34