[英]Converting byte array to bitmap gives bitmap=null in java
我正在嘗試做一些非常簡單的事情,但結果卻並非如此簡單。 我有一個位圖圖像,我必須將其轉換為字節以通過套接字發送。 字節數組發送正確(我已經檢查過),但是當我轉換回位圖時,會得到bitmap = null結果。 我相信我的錯誤在於我如何將原始位圖轉換為字節,或者嘗試將字節轉換回位圖。
在調試時,我意識到如果我將位圖轉換為字節,然后再將其轉換回位圖(不通過套接字發送),則它也為null。 這是我的代碼: 如何將位圖轉換為字節,然后再將字節轉換回位圖圖像?
// 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();
我在互聯網上搜索,最后發現一個人遇到了同樣的問題,其中位圖返回null,這是解決方法! 由於某種原因,它首先將字節數組轉換為jpeg,然后再轉換為位圖:
// Convert data to jpeg first then to bitmap (cant convert byte array directly to bitmap)
YuvImage yuvimage=new YuvImage(data, ImageFormat.NV21, 100, 100, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
yuvimage.compressToJpeg(new Rect(0, 0, 100, 100), 80, baos);
byte[] jdata = baos.toByteArray();
// Convert to Bitmap
Bitmap bmp = BitmapFactory.decodeByteArray(jdata, 0, jdata.length);
System.out.println("Bitmap Name 3" + bmp);
我在創建字節數組的位置下面添加了此代碼。 因此,我在這里稱為“數據”的變量是按字節數組排列的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.