I need to convert an image into a byte array in my Codename One app.
It will be used to create a base64 representation of the image to be used in a BrowserComponent.
I tried this:
byte[] bytes=new byte[10];
String base64IconString="data:image/png;base64,";
try(InputStream is = getClass().getResourceAsStream("/icon.png");) {
bytes=new byte[is.available()];
// the instruction above is wrong. it will fail
// use Util.readInputStream(InputStream) in Codename One instead
// see comments
Util.readAll(is, bytes);
base64IconString+=Base64.encode(bytes);
} catch(IOException err) {
Log.e(err);
}
I put the result into this:
browserComponent.setPage("<HTML><BODY>" + "<img src='"+base64IconString+"' />" + "</BODY></HTML>");
It works, but I need to create the base64 string from a Image that has no path or file name because it is from a special class MyImageFromSVGSubset.
This tool is used to generate that class: https://www.codenameone.com/blog/flamingo-svg-transcoder.html
Note: the Image class in CodenameOne has also the int[] getRGB() method.
How to achieve my goal?
You can use ImageIO
which is designed exactly for that: converting an Image
to bytes. However, there's a slightly simpler hack. EncodedImage
supports this out of the box so:
EncodedImage em = EncodedImage.createFromImage(otherImage, jpegOrPNG);
byte[] data = em.getImageData();
Also see BrowserComponent.createDataURI(byte[], mime)
.