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

Asked

Viewed 1,404 times

3

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

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

I’m converting the section after Base64, in 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 write the generated byte[] to the bank.

First wanted to know how before recording in the bank, take the image type(png,ttf,jpg,psd) and convert to JPEG, and then generate an array of it and save to the database?

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

1 answer

2


To read an image, you can use the class Imagery. The read() method receives an Inputstream. I’m not familiar with Overload that directly receives a URL (does it recognize the "protocol" date:?), but it’s quite easy to convert to byte[] using a Bytearrayinputstream. Source format should be detected automatically.

To convert to another format, just take 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 obtain the generated bytes.

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

Note: if using Java 8, there is already an official (de)encoder of Base64, out of the package.Misc, which runs the risk of being removed (or made inaccessible) in future versions of Java.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.