How to convert image into byte array and byte array to base64 String in android?
Try this:
// convert from bitmap to byte array
public byte[] getBytesFromBitmap(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 70, stream);
return stream.toByteArray();
}
// get the base 64 string
String imgString = Base64.encodeToString(getBytesFromBitmap(someImg),
Base64.NO_WRAP);
How can I convert an image into a Base64 string?
You can use the Base64 Android class:
String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
You'll have to convert your image into a byte array though. Here's an example:
Bitmap bm = BitmapFactory.decodeFile("/path/to/image.jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); // bm is the bitmap object
byte[] b = baos.toByteArray();
* Update *
If you're using an older SDK library (because you want it to work on phones with older versions of the OS) you won't have the Base64 class packaged in (since it just came out in API level 8 AKA version 2.2).
Check this article out for a workaround:
How to base64 encode decode Android
Convert selected image into byte array and into string
To convert image to string, use following short of code.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
yourbitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
//this will convert image to byte[]
byte[] byteArrayImage = baos.toByteArray();
// this will convert byte[] to string
String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
Now, you have encodedImage string of image.
Your code of "saveItem()" looks like following.
private void saveItem() {
// Client-Server - Start //////////////////////////////////////
String name = inputname.getText().toString();
String description = inputnote.getText().toString();
// Encode the image file to String !! by using Base64
//String encodedImage = Base64.encodeToString(blob, Base64.DEFAULT);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
yourbitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
//this will convert image to byte[]
byte[] byteArrayImage = baos.toByteArray();
// this will convert byte[] to string
String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
// Building Parameters
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("name", name));
params1.add(new BasicNameValuePair("description", description));
params1.add(new BasicNameValuePair("photo",encodedImage));
Log.v("log_tag", System.currentTimeMillis()+".jpg");
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product, "POST", params1);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
Log.v("log_tag", "In the try Loop" );
if (success == 1) {
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
Passing image as a base64 encoded bytearray or just a path of it
The answer depends upon the quality of the image and its size ...suppose you have created an image gallery app that fetches image from the server and you want very high quality downloadable images....then you should use the image path
BUT
If you have an app that just uses the images as thumbnails or if the user has no use of the image you can use the base64 encoded image since its loading time is very fast and the heavylifting is done by the app and not the network...i.e loading the whole image through path takes time and much data while the base64 encoded image is just a small string which will be converted to image by the app and will minimise the loading time..
Convert Image object to Base64 String in Android
Just convert your base64 string into bitmap than load that bitmap into imageview using below code
byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
image.setImageBitmap(decodedByte);
convert base64 string to byte array in android
Use this Apache Commons Codec in your project.
byte[] decoded = org.apache.commons.codec.binary.Base64.decodeBase64(imageString.getBytes());
Or use Sun's options:
import sun.misc.BASE64Decoder;
byte[] byte;
try
{
BASE64Decoder decoder = new BASE64Decoder();
byte = decoder.decodeBuffer(imageString);
}
catch (Exception e)
{
e.printStackTrace();
}
converting image to byte array in android
public boolean compress (Bitmap.CompressFormat format, int quality, OutputStream stream)
Quality:
Hint to the compressor, 0-100. 0 meaning compress for small size, 100 meaning compress for max quality. Some formats, like PNG which is lossless, will ignore the quality setting.
Related Topics
Imageview Be a Square with Dynamic Width
How to Make a Vertical Seekbar in Android
How to Open a Different Activity on Recyclerview Item Onclick
How to Create a Circular (Endless) Recyclerview
Is There a Listener for When the Webview Displays It's Content
How to Retrieve Style Attributes Programmatically from Styles.Xml
How to Integrate Eclipse with Gradle in Android Project
How to Convert Views to Bitmaps
How to Group Radiobutton from Different Linearlayouts
Error: "Adb Connection Error:An Existing Connection Was Forcibly Closed by the Remote Host"
How to Restrict Android App to Specific Device Make
How to Convert Image into Byte Array and Byte Array to Base64 String in Android
Android: Clear Cache of All Apps
How to Find If a Particular Package Exists on My Android Device
How to Know When an Edittext Loses Focus
Android Failed to Load Js Bundle