BitmapFactory.decodeByteArray() 返回null,分析與解決


問題描述:用android自帶的Camera獲取圖片,上傳至遠程數據庫中(mysql),以BLOB格式存儲,

但在提取圖片時,始終無法在android界面顯示,示例代碼如下:

   .....  ....

   s = new Socket("192.168.0.68", 9999);
   din = new DataInputStream(s.getInputStream());

   ...   ...

   int size = din.readInt();//讀取服務器端傳來的圖片數據
   byte[] bs = new byte[size];
   din.read(bs);

   Bitmap b = BitmapFactory.decodeByteArray(bs,0,bs.length);
   

   Log.i("kkk00",String.valueOf(b));//輸出測試,bitmap始終為NUll

 

解決方法:

方法1:增加轉碼處理

   int size = din.readInt();//讀取服務器端傳來的圖片數據
   byte[] bs = new byte[size];
   din.read(bs);

   YuvImage yuvimage=new YuvImage(bs, ImageFormat.NV21, 20,20, null);//20、20分別是圖的寬度與高度
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       yuvimage.compressToJpeg(new Rect(0, 0,20, 20), 80, baos);//80--JPG圖片的質量[0-100],100最高
       byte[] jdata = baos.toByteArray();

       Bitmap bmp = BitmapFactory.decodeByteArray(jdata, 0, jdata.length);

測試:bmp不為空,放入控件中可正常顯示。

 

方法2:當圖片以二進制形式傳至服務器端時,將其存儲到本機上,在以文件流的形式存入mysql數據庫中

     .......

     int size = din.readInt();//讀取圖片數組的長度
     FileOutputStream fos = new FileOutputStream("c:/bbbb1.bmp"); 
     int len=0;
     byte[] mm=new byte[1024];
     while(true) {
      int m=din.read(mm);
      len=len+m;
      fos.write(mm,0,m);
      if(len>=size) break; 
     }
     fos.close();

     

    //在讀取文件寫入mysql

    ..... ...

     File file = new File("c:/bbbb1.bmp");  
     int length = (int) file.length();   
    InputStream fin = new FileInputStream(file); 
    pstmt.setBinaryStream (9, fin, length);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM