I am trying to do something very simple that has ended up not so simple. I have a bitmap image and I have to convert it to bytes to send over a socket. The byte array sends over correctly ( I have checked), but when I convert back to a bitmap, I get bitmap=null results. I believe my error is in how I am converting my original bitmap to bytes, or when I try to turn my bytes back into a bitmap.
As I was debugging I realized that if I take my bitmap, convert it to bytes, and then convert it right back to a bitmap (without sending it over the socket) it is also null. Here is my code: How can I convert a bitmap to bytes, and then bytes back into a bitmap image?
// I am getting my image from ApplicationInfo and I know I am getting it because I have opened it on my computer after extracting it
Drawable icon = context.getPackageManager().getApplicationIcon(ai);
Log.d("tag_name", "ICON" + icon);
BitmapDrawable bitmapIcon = (BitmapDrawable)icon;
Log.d("tag_name", "BITMAP Drawable" + bitmapIcon);
// STREAM IMAGE DATA TO FILE
// This is how I know I am correctly getting my png image (no errors here)
FileOutputStream fosIcon = context.openFileOutput(applicationName + ".png", Context.MODE_PRIVATE);
bitmapIcon.getBitmap().compress(Bitmap.CompressFormat.PNG, 100, fosIcon);
InputStream inputStream = context.openFileInput(applicationName + ".png");
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
Log.d("tag_name", "BITMAP NAME" + bitmap);
// get bitmap image in bytes to send
int bytes = bitmap.getByteCount();
Log.d("tag_name", "Number of Bytes" + bytes);
ByteBuffer buffer = ByteBuffer.allocate(bytes); //Create a new buffer
bitmap.copyPixelsToBuffer(buffer); //Move the byte data to the buffer
byte[] array = buffer.array();
Log.d("tag_name", "array" + array);
int start=0;
int len=array.length;
Log.d("tag_name", "length" + len);
if (len < 0)
throw new IllegalArgumentException("Negative length not allowed");
if (start < 0 || start >= array.length)
throw new IndexOutOfBoundsException("Out of bounds: " + start);
// Convert BACK TO bitmap (this will be done on the other side of my socket, but it is also null here???
Bitmap bitmap_2 = BitmapFactory.decodeByteArray(array , 0, array.length);
System.out.println("Bitmap Name 2" + bitmap_2);
// Open SendToClient Class to send string and image over socket
new SendToClient(array, applicationName, len, start, packagename).execute();
startandlenfor values which they cannot possibly have?int start = 0;and two lines you are checking that it isn't negative. You haveint len = array.length;and two lines later you are checking that it isn't negative.startcan't be negative, and neither canlen, given these initializations.