Sometimes we stocked during image processing in android in to ImageView, if will be be through exception.
Here is the some image convert in to bitmap and reverse process.
Convert Drawable image in to bitmap:
Bitmap profimeBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.profile);
Another methods, if above not working
public Bitmap convertToBitmap(Drawable profile, int widthPixels, int heightPixels) {
Bitmap profileBitmap = Bitmap.createBitmap(widthPixels, heightPixels, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(profileBitmap);
profile.setBounds(0, 0, widthPixels, heightPixels);
profile.draw(canvas);
return profileBitmap;
}
Getting Bitmap from image url
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
Convert Bitmap type image to Drawable,
Drawable drawableProfile = new BitmapDrawable(getResources(), bitmapProfile);
Covert Bitmap to BitmapDrawable
BitmapDrawable bdProfile= new BitmapDrawable(bitmapProfile);
Retrive Bitmap when you set bitmap image on imageview,
imageView.setImageBitmap(profileBitmap);
Now, getting bitmap from imageView ,
Bitmap bitmapProfile = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
Convert from bitmap to byte array:
public byte[] getBytesFromBitmap(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 70, stream);
return stream.toByteArray();
}
Convert SD Card Image to Bitmap to Byte Array:
String path="/path/images/image.jpg";
public byte[] getBytesFromBitmap(String path) {
Bitmap bitmap = BitmapFactory.decodeFile(path);
ByteArrayOutputStream blob = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 , blob);
byte[] bitmapdata = blob.toByteArray();
return bitmapdata;
}
Convert from byte array to bitmap:
Bitmap bitmapProfile = BitmapFactory.decodeByteArray(bitmapbyteArraydata , 0, bitmapbyteArraydata .length);
OR
public Bitmap ByteArrayToBitmap(byte[] byteArray)
{
ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(byteArray);
Bitmap bitmapProfile = BitmapFactory.decodeStream(arrayInputStream);
return bitmapProfile;
}
Featured Post
Implementing Hilt in a Kotlin Android Jetpack Compose Project with MVVM Architecture
In modern Android development, maintaining a scalable codebase can be challenging, especially when it comes to dependency management. Hilt,...
Android Tutorials
Home
Android
Android Tutorials
Image Convert to Bitmap, ByteArray, Drawable in Android or Android studio