2013-11-04 34 views
4

我已經在這個問題上掙扎了2天......之前發佈過,但沒有答案是正確的。如何將圖像(字節數組)從JSON顯示到imageView ...工廠返回null

我的問題是:我試圖將字節[]轉換爲圖像。字節[]來自JSON和它的格式如下:

「4oCwUE5HDQoaCgAAAA1JSERSAAAAfwAAAFAIBgAAADBHwqrDsAAAAAlwSFlzAAAAJwAAACcBKgnigJhPAAAgAElEQVR4xZPCrMK9ecWSZcOZfcOfw7c5w5vCvW/CqXp ......」時,轉到另一個100行。

類用於顯示圖像:

public class PlayersListActivity extends Activity { 

// URL to make request 
private static String URL = "url goes here"; 
private static int userID; 
ArrayList<HashMap<String, Object>> playersList; 
ListView playerView; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.list_view); 

    Bundle extras = getIntent().getExtras(); 
    userID = extras.getInt("id"); 
    initLayout(); 
} 

private void initLayout() { 

    playerView = (ListView) findViewById(R.id.list); 
    playersList = new ArrayList<HashMap<String, Object>>(); 

    playerView.setAdapter(new SimpleAdapter(PlayersListActivity.this, playersList, R.layout.activity_players_list, null, null)); 


    playerView.setDividerHeight(0); 

} 

@Override 
protected void onResume() { 
    if (!ConnectivityStatus.isNetworkAvailable(getApplicationContext())) { 
     Toast.makeText(PlayersListActivity.this, R.string.network_failed, 
       Toast.LENGTH_SHORT).show(); 
    } else { 
     playerView.setAdapter(null); 
     new PlayersLoadTask().execute(); 
    } 

    super.onResume(); 
} 

ProgressDialog pDialog; 

class PlayersLoadTask extends AsyncTask<String, String, String> { 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     pDialog = new ProgressDialog(PlayersListActivity.this); 
     pDialog.setMessage("Reading data"); 
     pDialog.setIndeterminate(false); 
     pDialog.setCancelable(true); 
     pDialog.show(); 
     playersList.clear(); 
    } 
    @Override 
    protected String doInBackground(String... arg0) { 
     try { 

     ArrayList<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>(); 
     parameters.add(new BasicNameValuePair("request", "getPlayers")); 
     parameters.add(new BasicNameValuePair("clubid", Integer.toString(userID))); // TODO: you'll need to change this to the Id from the user 

     DefaultHttpClient httpClient = new DefaultHttpClient(); 
     HttpPost httpPost = new HttpPost(PlayersListActivity.URL); 
     httpPost.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8")); 
     HttpResponse httpResponse = httpClient.execute(httpPost); 
     HttpEntity httpEntity = httpResponse.getEntity(); 

     // if this is null the web service returned an empty page 
     if(httpEntity == null) // response is empty so exit out 
      return null; 

     String jsonString = EntityUtils.toString(httpEntity); 

     // again some simple validation around the returned string 
     if(jsonString != null && jsonString.length() != 0) // checking string returned from service to grab id 
     { 
      JSONArray jsonArray = new JSONArray(jsonString); 
      for(int i=0; i< jsonArray.length(); i++) 
      { 
       HashMap<String, Object> map = new HashMap<String, Object>(); 

       JSONObject jsonObject = (JSONObject) jsonArray.get(i); 
       int id = jsonObject.getInt("id"); 
       String name = jsonObject.getString("name"); 
       byte[] image = jsonObject.getString("image").getBytes(); 
       String base64 = jsonObject.getString("image"); 
       try { 
        BitmapFactory.Options op=new BitmapFactory.Options(); 
        op.inSampleSize=8; 
        Bitmap yourSelectedImage = BitmapFactory.decodeByteArray(image,0,image.length); 
        ByteArrayOutputStream baos = new ByteArrayOutputStream(); 

        yourSelectedImage.compress(Bitmap.CompressFormat.PNG, 100, baos); 
        //this will convert image to byte[] 
        byte[] byteArrayImage = baos.toByteArray(); 
        // this will convert byte[] to string 
        String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT); 
        if (encodedImage != null) { 

         ImageView imgView = (ImageView) findViewById(R.id.image); 
         imgView.setImageBitmap(yourSelectedImage); 
        } 

       } catch (Exception e) { 
        Log.d("Exception", e.toString()); 
       } 
       //map.put("id", id); 
       map.put("image", base64.toString()); 
       map.put("name", name); 

       //Log.d("JSON OBJECTS:", jsonObject.toString()); 
       //Log.d("WHATS IN MAP:", map.toString()); 

       playersList.add(map); 
      } 

     } 
    } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } catch (Exception e) { 
     Log.e("ERROR SOMEWHERE!!!! " , e.toString()); 
    } 
    return null; 

    } 

    protected void onPostExecute(String file_url) { 
     if(playersList.size() == 0) { 
      Toast.makeText(PlayersListActivity.this, "No players in a list" , Toast.LENGTH_SHORT).show(); 
     } else { 
      playerView.setAdapter(new PlayerListAdapter (PlayersListActivity.this, playersList, R.layout.activity_players_list, new String[] {"id", "image", "name"}, new int[] {R.id.player_list_id, R.id.image, R.id.name, })); 
     } 

     pDialog.dismiss(); 
    } 
} 

}

而且logcat的:

D/skia(3513): --- SkImageDecoder::Factory returned null 
D/skia(3513): --- SkImageDecoder::Factory returned null 
E/BitmapFactory(4399): Unable to decode stream: java.io.FileNotFoundException: /4oCwUE5HDQoaCgAAAA1JSERSAAAAfwAAAFAIBgAAADBHwqrDsAAAAAlwSFlzAAAAJwAAACcBKgnigJhPAAAgAElEQVR4xZPCrMK9ecWSZcOZfcOfw7c5w5vCvW/CqXpLV... 

我不知道在所有的,爲什麼我的位圖返回null。我嘗試了許多不同的方式,但沒有任何作用。

這就是爲什麼我需要幫助不好!謝謝!!!

+0

確定。但我也嘗試過使用String,但沒有奏效。 – Jakubee

+0

你是從它得到編碼的基礎64字符串或它返回空 –

+0

你的意思是這樣的: ByteArrayOutputStream stream = new ByteArrayOutputStream(); byte [] byteArray = stream.toByteArray(); String base64 = Base64.encodeToString(byteArray,0); 它返回null。 – Jakubee

回答

8

供將來參考

JSONArray jsonArray = new JSONArray(jsonString); 
for (int i = 0; i < jsonArray.length(); i++) { 
    HashMap<String, Object> map = new HashMap<String, Object>(); 
    JSONObject jsonObject = (JSONObject) jsonArray.get(i); 
    int id = jsonObject.getInt("id"); 
    String name = jsonObject.getString("name"); 


    byte[] byteArray = Base64.decode(jsonObject.getString("image"), Base64.DEFAULT) ; 
    Bitmap bmp1 = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length); 
    //Bitmap bitmap = Bitmap.createScaledBitmap(bmp1, 120, 120, false); 


    map.put("id", id); 
    map.put("name", name); 

    map.put("image", bmp1); 


    playersList.add(map); 
    //Log.d("SHOW PLAYER LIST: " ,playersList.toString()); 
} 
+0

它沒有爲我工作仍返回位圖值爲空 –

+0

Tnx很多朋友。它的工作對我來說 –

+0

@RajaPriyan for(int i = 0; i Varma

0
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray , 0, byteArray .length); 
iv.setImageBitmap(bitmap); 

該代碼將簡單地解碼來自字節數組的圖像。

+0

位圖顯示空 – Jakubee

+0

如果圖像很大,那麼它顯示'OutOfMemmoryError',所以Jakubee的答案是正確的! –

1

轉換位圖字節數組: -

Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher); ByteArrayOutputStream stream = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.PNG, 100, stream); byte[] byteArray = stream.toByteArray();

轉換字節數組的位圖: `BMP位= BitmapFactory.decodeByteArray(字節陣列,0,byteArray.length); ImageView image =(ImageView)findViewById(R.id.imageView1);

image.setImageBitmap(BMP);`

+0

解碼來自項目的圖像。那麼json的字節數組呢? – Jakubee

+0

Bmp返回null – Jakubee

+0

http://stackoverflow.com/questions/7427089/how-to-download-base64-data-partly-from-web-server-and-decode-partly-from-encode--try此鏈接 – Mohan

相關問題