Skip to content

Instantly share code, notes, and snippets.

@xjohnxjohn
Forked from vvkirillov/BitmapUtils.java
Created February 6, 2018 01:28
Show Gist options
  • Save xjohnxjohn/a44e912c61dc7df2b7e17ba10f202a23 to your computer and use it in GitHub Desktop.
Save xjohnxjohn/a44e912c61dc7df2b7e17ba10f202a23 to your computer and use it in GitHub Desktop.
Android bitmap conversion to and from byte array
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
public final class BitmapUtils {
private BitmapUtils(){}
/**
* Converts bitmap to byte array in PNG format
* @param bitmap source bitmap
* @return result byte array
*/
public static byte[] convertBitmapToByteArray(Bitmap bitmap){
ByteArrayOutputStream baos = null;
try {
baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}finally {
if(baos != null){
try {
baos.close();
} catch (IOException e) {
Log.e(BitmapUtils.class.getSimpleName(), "ByteArrayOutputStream was not closed");
}
}
}
}
/**
* Converts bitmap to the byte array without compression
* @param bitmap source bitmap
* @return result byte array
*/
public static byte[] convertBitmapToByteArrayUncompressed(Bitmap bitmap){
ByteBuffer byteBuffer = ByteBuffer.allocate(bitmap.getByteCount());
bitmap.copyPixelsToBuffer(byteBuffer);
byteBuffer.rewind();
return byteBuffer.array();
}
/**
* Converts compressed byte array to bitmap
* @param src source array
* @return result bitmap
*/
public static Bitmap convertCompressedByteArrayToBitmap(byte[] src){
return BitmapFactory.decodeByteArray(src, 0, src.length);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment