How to convert image into byte array and byte array to base64 String in android? How to convert image into byte array and byte array to base64 String in android? arrays arrays

How to convert image into byte array and byte array to base64 String in android?


Try this:

// convert from bitmap to byte arraypublic byte[] getBytesFromBitmap(Bitmap bitmap) {    ByteArrayOutputStream stream = new ByteArrayOutputStream();    bitmap.compress(CompressFormat.JPEG, 70, stream);    return stream.toByteArray();}// get the base 64 stringString imgString = Base64.encodeToString(getBytesFromBitmap(someImg),                        Base64.NO_WRAP);


I wrote the following code to convert an image from sdcard to a Base64 encoded string to send as a JSON object.And it works great:

String filepath = "/sdcard/temp.png";File imagefile = new File(filepath);FileInputStream fis = null;try {    fis = new FileInputStream(imagefile);    } catch (FileNotFoundException e) {    e.printStackTrace();}Bitmap bm = BitmapFactory.decodeStream(fis);ByteArrayOutputStream baos = new ByteArrayOutputStream();  bm.compress(Bitmap.CompressFormat.JPEG, 100 , baos);    byte[] b = baos.toByteArray(); encImage = Base64.encodeToString(b, Base64.DEFAULT);


They have wrapped most stuff need to solve your problem, one of the tests looks like this:

String filename = CSSURLEmbedderTest.class.getResource("folder.png").getPath().replace("%20", " ");String code = "background: url(folder.png);";StringWriter writer = new StringWriter();embedder = new CSSURLEmbedder(new StringReader(code), true);embedder.embedImages(writer, filename.substring(0, filename.lastIndexOf("/")+1));String result = writer.toString();assertEquals("background: url(" + folderDataURI + ");", result);