如何将图像(字节数组)从 JSON 显示到 imageView 中...工厂返回 null [英] How to display image (byte array) from JSON into imageView... Factory returns null

查看:10
本文介绍了如何将图像(字节数组)从 JSON 显示到 imageView 中...工厂返回 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在这个问题上苦苦挣扎 2 天了...之前发过帖子,但没有一个答案是正确的.

我的问题是:我正在尝试将 byte[] 转换为图像.byte[] 来自 JSON,它的格式如下:

4oCwUE5HDQoaCgAAAA1JSERSAAAAfwAAAFAIBgAAADBHwqrDsAAAAAlwSFlzAAAAJwAAACcBKgnigJhPAAAgAElEQVR4xZPCrMK9ecWSZcOZfcOfw7c5w5vCvW/CqXp..."

用于显示图像的类:

public class PlayersListActivity extends Activity {//发出请求的 URLprivate static String URL = "url 到这里";私有静态 int 用户 ID;ArrayList>球员名单;ListView playerView;@覆盖protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.list_view);捆绑额外费用 = getIntent().getExtras();userID = extras.getInt("id");initLayout();}私有无效initLayout(){playerView = (ListView) findViewById(R.id.list);playerList = new ArrayList>();playerView.setAdapter(new SimpleAdapter(PlayersListActivity.this, playerList, R.layout.activity_players_list, null, null));playerView.setDividerHeight(0);}@覆盖受保护的无效 onResume() {如果(!ConnectivityStatus.isNetworkAvailable(getApplicationContext())){Toast.makeText(PlayersListActivity.this, R.string.network_failed,Toast.LENGTH_SHORT).show();} 别的 {playerView.setAdapter(null);new PlayersLoadTask().execute();}super.onResume();}ProgressDialog pDialog;类 PlayersLoadTask 扩展了 AsyncTask{@覆盖受保护的无效 onPreExecute() {super.onPreExecute();pDialog = new ProgressDialog(PlayersListActivity.this);pDialog.setMessage("读取数据");pDialog.setIndeterminate(false);pDialog.setCancelable(true);pDialog.show();球员名单.clear();}@覆盖受保护的字符串 doInBackground(字符串... arg0){尝试 {ArrayList参数 = 新的 ArrayList();parameters.add(new BasicNameValuePair("request", "getPlayers"));parameters.add(new BasicNameValuePair("clubid", Integer.toString(userID)));//TODO:您需要将其更改为用户的 IdDefaultHttpClient 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();//如果为 null,则 Web 服务返回一个空页面if(httpEntity == null)//响应为空所以退出返回空;String jsonString = EntityUtils.toString(httpEntity);//再次对返回的字符串进行一些简单的验证if(jsonString != null && jsonString.length() != 0)//检查服务返回的字符串以获取id{JSONArray jsonArray = new JSONArray(jsonString);for(int i=0; i< jsonArray.length(); i++){HashMap<字符串,对象>map = new HashMap();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");尝试 {BitmapFactory.Options op=new BitmapFactory.Options();op.inSampleSize=8;位图 yourSelectedImage = BitmapFactory.decodeByteArray(image,0,image.length);ByteArrayOutputStream baos = new ByteArrayOutputStream();yourSelectedImage.compress(Bitmap.CompressFormat.PNG, 100, baos);//这会将图像转换为字节[]byte[] byteArrayImage = baos.toByteArray();//这会将 byte[] 转换为字符串String encodingImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);如果(编码图像!= null){ImageView imgView = (ImageView) findViewById(R.id.image);imgView.setImageBitmap(yourSelectedImage);}} 捕获(异常 e){Log.d("异常", e.toString());}//map.put("id", id);map.put("image", base64.toString());map.put("name", name);//Log.d("JSON 对象:", jsonObject.toString());//Log.d("地图中的内容:", map.toString());玩家列表.添加(地图);}}} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (JSONException e) {e.printStackTrace();} 捕获(异常 e){Log.e("某处出错!!!!" , e.toString());}返回空;}protected void onPostExecute(String file_url) {if(playersList.size() == 0 ) {Toast.makeText(PlayersListActivity.this, "列表中没有玩家" , Toast.LENGTH_SHORT).show();} 别的 {playerView.setAdapter(new PlayerListAdapter (PlayersListActivity.this, playerList, 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 返回 nullD/skia(3513): --- SkImageDecoder::Factory 返回 nullE/BitmapFactory(4399):无法解码流:java.io.FileNotFoundException:/4oCwUE5HDQoaCgAAAA1JSERSAAAAfwAAAFAIBgAAADBHwqrDsAAAAAlwSFlzAAAAJwAAACcBKgnigJhPAAAgAElEQVR4xZPCrMK7fwAAAFAIBg

我完全不知道为什么我的 Bitmap 返回 null.我尝试了很多不同的方法,但没有任何效果.

这就是为什么我非常需要帮助!谢谢!!!

解决方案

供以后参考

JSONArray jsonArray = new JSONArray(jsonString);for (int i = 0; i < jsonArray.length(); i++) {HashMap<字符串,对象>map = new HashMap();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) ;位图 bmp1 = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);//位图 bitmap = Bitmap.createScaledBitmap(bmp1, 120, 120, false);map.put("id", id);map.put("name", name);map.put("图片", bmp1);玩家列表.添加(地图);//Log.d("SHOW PLAYER LIST: " ,playersList.toString());}

I'm struggling with this problem 2 days already... Was posting before but non of the answers were right.

My problem is: i'm trying to convert byte[] into image. The byte[] comes from JSON and it's in this format:

"4oCwUE5HDQoaCgAAAA1JSERSAAAAfwAAAFAIBgAAADBHwqrDsAAAAAlwSFlzAAAAJwAAACcBKgnigJhPAAAgAElEQVR4xZPCrMK9ecWSZcOZfcOfw7c5w5vCvW/CqXp..." it goes for another 100 lines.

Class for displaying the images:

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();
    } 
}

}

And the 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...

I have no idea at all why my Bitmap return null. I have tried many different ways but nothing works.

That's why I need help badly! Thanks!!!

解决方案

For future reference

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());
}

这篇关于如何将图像(字节数组)从 JSON 显示到 imageView 中...工厂返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆