2015-07-21 68 views
0

我有從網址查看的JSON數據。 JSON數組中有許多JSON對象,其中一個是jpeg圖像。在Android中解碼jpeg

我想將該圖像發送到Android應用程序的列表視圖。

現在我有圖像JSON對象鏈接到我的Java文件中的私有靜態最終字符串標記。但是,我意識到我必須解碼圖像,否則我將收到以下錯誤:無法解碼流:java.io.FileNotFoundException和resolveUri在錯誤的位圖uri上失敗。

我正在進行長期不斷的搜索以瞭解如何解碼JSON jpeg圖像,大部分此類研究都是通過查看本網站上的帖子進行的,因此請不要將其標記爲重複問題。

public class JSONBuilderActivity extends ListActivity { 

    private ProgressDialog pDialog; 

    //URL to get JSON 
    private static String url = ""; 

    //JSON Node names 
    private static final String TAG_CARS = "cars";  //root 
    private static final String TAG_CARID = "CarID"; 
    private static final String TAG_CARVIN = "CarVIN"; 
    private static final String TAG_IMG= "CarMainImage"; 

    JSONArray carid = null; //Initializes JSON array 

    static String response = null; 

    //Hashmap for ListView 
    ArrayList<HashMap<String, Object>>caridList; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     ListView lv = getListView(); 

     //Listview on item click listener 
     lv.setOnItemClickListener(new OnItemClickListener() { 

      @Override 
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 

       //Gets values from selected ListItem 
       String cars = ((TextView) view.findViewById(R.id.cars)).getText().toString(); 
       String car_id = ((TextView) view.findViewById(R.id.car_id)).getText().toString(); 
       String car_vin = ((TextView) view.findViewById(R.id.car_vin)).getText().toString(); 
       String model_img = ((ImageView) view.findViewById(R.id.model_img)).getTag().toString(); 

       Intent in = new Intent(JSONBuilderActivity.this, MainActivity.class); 
       //Sends data to MainActivity 
       in.putExtra("TAG_CARS", cars); 
       in.putExtra("TAG_CARID", car_id); 
       in.putExtra("TAG_CarVin", car_vin); 
       in.putExtra("TAG_IMG", model_img); 
       startActivity(in); 
      } 
     }); 

     //Calls async task to get json 
     new GetCars().execute(); 
    } 

    public class ServiceHandler { 

     public final static int GET = 1; 
     public final static int POST = 2; 

     public ServiceHandler() { 

     } 

     /** 
     * Makes service call 
     * @url - url to make request 
     * @method - http request method 
     * */ 
     public String makeServiceCall(String url, int method) { 
      return this.makeServiceCall(url, method, null); 
     } 

     /** 
     * Makes service call 
     * @url - url to make request 
     * @method - http request method 
     * @params - http request params 
     * */ 
     public String makeServiceCall(String url, int method,ArrayList<NameValuePair> params) { 
        try { 
        DefaultHttpClient httpClient = new DefaultHttpClient(); 
        HttpEntity httpEntity = null; 
        HttpResponse httpResponse = null; 

        //Checks http request method type 
        if (method == POST) { 
         HttpPost httpPost = new HttpPost(url); 

         //Adds post params 
        if (params != null) { 
         httpPost.setEntity(new UrlEncodedFormEntity(params)); 
        } 

         httpResponse = httpClient.execute(httpPost); 

       } else if (method == GET) { 

        //Appends params to url 
        if (params != null) { 
         String paramString = URLEncodedUtils.format(params, "utf-8"); 
         url += "?" + paramString; 
        } 
         HttpGet httpGet = new HttpGet(url); 

         httpResponse = httpClient.execute(httpGet); 
       } 

       httpEntity = httpResponse.getEntity(); 
       response = EntityUtils.toString(httpEntity); 

      } catch (UnsupportedEncodingException e) { 
       e.printStackTrace(); 
      } catch (ClientProtocolException e) { 
       e.printStackTrace(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 

      return response; 

     } 
    } 

    /* 
    * Async task class to get json by making HTTP call 
    */ 
    private class GetCars extends AsyncTask<Void, Void, Void> { 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      caridList = new ArrayList<HashMap<String, Object>>(); 

      //Shows progress dialog 
      pDialog = new ProgressDialog(JSONBuilderActivity.this); 
      pDialog.setMessage("Please wait..."); 
      pDialog.setCancelable(false); 
      pDialog.show(); 

     } 

     @Override 
     protected Void doInBackground(Void... arg0) { 

      //Creates service handler class instance 
      ServiceHandler sh = new ServiceHandler(); 

      //Makes a request to url and getting response 
      String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET); 

      //Prints the json response in the log 
      Log.d("GetCars response: ", "> " + jsonStr); 

        if (jsonStr != null) { 
         try { 

          Log.d("try", "in the try"); 

          JSONObject jsonObj = new JSONObject(jsonStr); 
          Log.d("jsonObject", "new json Object"); 

          //Gets JSON Array node 
          carid = jsonObj.getJSONArray(TAG_CARS); 
          Log.d("json array", "user point array"); 

          int len = carid.length(); 
          Log.d("len", "get array length"); 

          for (int i = 0; i < carid.length(); i++) { 
           JSONObject c = carid.getJSONObject(i); 
           String car_id = c.getString(TAG_CARID); 
           Log.d("car_id", car_id); 

           String car_vin = c.getString(TAG_CARVIN); 
           Log.d("car_vin", car_vin); 


           BitmapFactory.Options options = new BitmapFactory.Options(); 
           options.inJustDecodeBounds = true; 
           BitmapFactory.decodeResource(getResources(), R.id.model_img, options); 
           int imageHeight = options.outHeight; 
           int imageWidth = options.outWidth; 
           String imageType = options.outMimeType; 


           // byte[] byteArray = Base64.decode(jsonObj.getString(TAG_IMG), Base64.DEFAULT) ; 
           //Bitmap bmp1 = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length); 

           //String model_img = c.getString(TAG_IMG); 
           //Log.d("model_img", model_img); 

           //Hashmap for single match 
           HashMap<String, Object> matchGetCars = new HashMap<String, Object>(); 

           //Adds each child node to HashMap key => value 
           matchGetCars.put(TAG_CARID, car_id); 
           matchGetCars.put(TAG_CARVIN, car_vin); 
           matchGetCars.put(TAG_IMG, ); //idk 
           caridList.add(matchGetCars); 
          } 
         } catch (JSONException e) { 
          e.printStackTrace(); 
         } 
        } else { 
         Log.e("ServiceHandler", "Couldn't get any data from the url"); 
        } 

        return null; 
       } 

     @Override 
       protected void onPostExecute(Void result) { 
        super.onPostExecute(result); 
        //Dismisses the progress dialog 
        if (pDialog.isShowing()) 
         pDialog.dismiss(); 

        /** 
        * Updates parsed JSON data into ListView 
        * */ 
        ListAdapter adapter = new SimpleAdapter(JSONBuilderActivity.this, caridList, R.layout.list_item, 
          new String[]{TAG_CARID, TAG_CARVIN, TAG_IMG}, new int[]{R.id.car_id, R.id.car_vin, R.id.model_img}); 
        setListAdapter(adapter); 
        Log.v("List parsed", caridList.toString()); 
       } 
    } 

因此,如何解碼JSON JPEG圖像的任何建議將不勝感激。謝謝。

} 

更新:

public Uri getImageUri(Context inContext, Bitmap inImage){ 
     ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
     inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes); 
     String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "CarMainImage", null); 
     return Uri.parse(path); 
    } 

    public void saveBmpToFile(File filename, Bitmap bmp){ 
     FileOutputStream out = null; 
     try { 
      out = new FileOutputStream(filename); 
      bmp.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance 
      // PNG is a lossless format, the compression factor (100) is ignored 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       if (out != null) { 
        out.close(); 
       } 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
    //------------------------ 
    public boolean renameFileExtension(String source, String newExtension) 
    { 
     String target; 
     String currentExtension = getFileExtension(source); 

     if (currentExtension.equals("")) 
     { 
      target = source + "." + newExtension; 
     } 
     else 
     { 
      target = source.replaceFirst(Pattern.quote("." + 
        currentExtension) + "$", Matcher.quoteReplacement("." + newExtension)); 

     } 
     return new File(source).renameTo(new File(target)); 
    } 
    //--------------------------------------------------- 
    public String getFileExtension(String f) 
    { 
     String ext = ""; 
     int i = f.lastIndexOf('.'); 
     if (i > 0 && i < f.length() - 1) 
     { 
      ext = f.substring(i + 1); 
     } 
     return ext; 
    } 
    /* 
    * Async task class to get json by making HTTP call 
    */ 
    private class GetCars extends AsyncTask<Void, Void, Void> { 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      caridList = new ArrayList<HashMap<String, Object>>(); 

      //Shows progress dialog 
      pDialog = new ProgressDialog(JSONBuilderActivity.this); 
      pDialog.setMessage("Please wait..."); 
      pDialog.setCancelable(false); 
      pDialog.show(); 

     } 

     @Override 
     protected Void doInBackground(Void... arg0) { 

      //Creates service handler class instance 
      ServiceHandler sh = new ServiceHandler(); 

      //Makes a request to url and getting response 
      String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET); 

      //Prints the json response in the log 
      Log.d("GetCars response: ", "> " + jsonStr); 

      if (jsonStr != null) { 
       try { 

        Log.d("try", "in the try"); 

        JSONObject jsonObj = new JSONObject(jsonStr); 
        Log.d("jsonObject", "new json Object"); 

        //Gets JSON Array node 
        carid = jsonObj.getJSONArray(TAG_CARS); 
        Log.d("json array", "user point array"); 

        int len = carid.length(); 
        Log.d("len", "get array length"); 

        for (int i = 0; i < carid.length(); i++) { 
         JSONObject c = carid.getJSONObject(i); 
         String car_id = c.getString(TAG_CARID); 
         Log.d("car_id", car_id); 

         String car_vin = c.getString(TAG_CARVIN); 
         Log.d("car_vin", car_vin); 


         String model_img=c.getString(TAG_IMG); 
         // byte[] byteArray = Base64.decode(jsonObj.getString(TAG_IMG), Base64.DEFAULT) ; 
         //Bitmap bmp1 = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length); 

         // String model_img = c.getString(TAG_IMG); 
         //Log.d("model_img", model_img); 

         //Hashmap for single match 
         HashMap<String, Object> matchGetCars = new HashMap<String, Object>(); 

         //Adds each child node to HashMap key => value 
         matchGetCars.put(TAG_CARID, car_id); 
         matchGetCars.put(TAG_CARVIN, car_vin); 
         matchGetCars.put(TAG_IMG, model_img); 
         caridList.add(matchGetCars); 
        } 
       } catch (JSONException e) { 
        e.printStackTrace(); 
       } 
      } else { 
       Log.e("ServiceHandler", "Couldn't get any data from the url"); 
      } 

      return null; 
     } 




     @Override 
     protected void onPostExecute(Void result) { 
      super.onPostExecute(result); 
      //Dismisses the progress dialog 
      if (pDialog.isShowing()) 
       pDialog.dismiss(); 

      /** 
      * Updates parsed JSON data into ListView 
      * */ 
      ListAdapter adapter = new SimpleAdapter(JSONBuilderActivity.this, caridList, R.layout.list_item, 
        new String[]{TAG_CARID, TAG_CARVIN, TAG_IMG}, new int[]{R.id.car_id, R.id.car_vin, R.id.model_img}); 
      setListAdapter(adapter); 
      Log.v("List parsed", caridList.toString()); 

     } 

    } 

的logcat:

V/List parsed﹕ [{CarMainImage=/images/image.php?w=200&i 
Unable to decode stream: java.io.FileNotFoundException: /images/image.php?w=200.... 
unable to resolveUri failed on bad bitmap uri: /images/image.php?w=200.... 

我不明白爲什麼解析列表正確記錄,然後將這些錯誤彈出。但是,URL中的JSON jpeg與日誌貓中的jpeg沒有完全格式化,因爲JSON中的jpeg如下所示:/images/image.php?w=200 ...以及logcat中的jpeg如下所示:/ images /image.php?200 ..所以區別在於......任何人都可以詳細說明,如果這可能會顯示錯誤消息,並/或提供修復錯誤的建議? 我非常願意研究並來回去了解你所建議的任何事情。謝謝。

+0

http://www.vogella.com/tutorials/AndroidListView/article.html#adapterperformance_holder看到,學習他的「觀點持有者」的格局,幫助IMG標籤與列表中的位圖上下文 –

+0

@RobertRowntree我將徹底研究這一點。謝謝! – JohnWilliams

回答

0
without thinking I will post you some conversion code: 
**this is a place holder.** 
required understanding: 
Bitmap 
Uri Provides an object representation of a "uniform resource identifier" 
URL (Universal resourse loacator) reference (an address) to a resource on the Internet. 
file extensions. *.png *.jpg 

    this will be up-dated when my brain is not without sleep ;O) 
more to come as I think , my brain hurts: 

    //------------------------ 
        public Uri getImageUri(Context inContext, Bitmap inImage) 
        { 
         ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
         inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes); 
         String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null); 
         return Uri.parse(path); 
        } 

        public void saveBmpToFile(File filename, Bitmap bmp) 
        { 
        FileOutputStream out = null; 
        try { 
         out = new FileOutputStream(filename); 
         bmp.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance 
         // PNG is a lossless format, the compression factor (100) is ignored 
        } catch (Exception e) { 
         e.printStackTrace(); 
        } finally { 
         try { 
          if (out != null) { 
           out.close(); 
          } 
         } catch (IOException e) { 
          e.printStackTrace(); 
         } 
        } 
        } 
    //------------------------ 
      public static boolean renameFileExtension(String source, String newExtension) 
      { 
      String target; 
      String currentExtension = getFileExtension(source); 

      if (currentExtension.equals("")) 
      { 
       target = source + "." + newExtension; 
      } 
      else 
      { 
       target = source.replaceFirst(Pattern.quote("." + 
        currentExtension) + "$", Matcher.quoteReplacement("." + newExtension)); 

      } 
      return new File(source).renameTo(new File(target)); 
      } 
     //--------------------------------------------------- 
      public static String getFileExtension(String f) 
      { 
      String ext = ""; 
      int i = f.lastIndexOf('.'); 
      if (i > 0 && i < f.length() - 1) 
      { 
       ext = f.substring(i + 1); 
      } 
      return ext; 
      } 
     //----------------------- 
+0

你好。是的,我從另一篇帖子記得你。謝謝你迴應這個。我想從存儲在URL中的JSON數據獲取jpeg,並將該圖像解碼爲在ListView中查看,而不是在我的Android應用程序中查看ImageView。最近,我一直在尋找畢加索的getView方法,迄今爲止沒有成功。和以前一樣,我仍然非常願意來回討論解決方案。 – JohnWilliams

+0

謝謝!我稍微編輯了一下你的代碼來解決一些問題。我正在研究URL和URI之間的區別,現在使用.jpg和位圖解碼。我也試圖現在使用圖像uri,並在doInBackground中包含uri信息,以將uri應用於與圖像相對應的TAG_IMG。此外,我正在嘗試拍攝該圖像,並在ListView和不ImageView中查看它。我期待收到你的來信。 – JohnWilliams

+0

熊與我一起我很忙,但我完全支持這個網站的精神 - 回饋一些東西。隨着時間的推移,建立一個你喜歡和理解的代碼庫。編碼是一個很大的承諾和回報。這些要點只是爲了好玩(上癮的本質不會被忽視!)。你的禮貌和熱情,是程序員的一個好開始。保持。我希望很多人幫助你建立你的技能和代碼庫。繼續黑客! –

0

任何BitmapFactory方法適合你嗎?有幾個可以採取字節數組並給你一個Bitmap。然後你可以很容易地把你的Bitmap放入ImageView

+0

謝謝!我將繼續研究BitmapFactory方法。但是,您可以請解釋我如何將我的位圖放入ListView而不是ImageView中? – JohnWilliams

+0

也許你可以編輯你的問題來畫出你期望它的樣子。如果您希望圖像位於視圖中的每個列表項目中,最好將ImageView放入列表項佈局文件中並將其填充到列表適配器中。如果你想要它作爲背景,那應該是一個相當直接的調用來設置一個視圖的背景。 – drdaanger

+0

嗨,我編輯了我的問題,以更徹底地解釋我想要做什麼。請看一下。謝謝! – JohnWilliams

0

我會建議使用Picasso

當你只需要提供你的圖像URL和內部getView您的ImageView(適配器)的功能。所有從url下載圖像到位圖轉換並設置爲圖像視圖的工作都將由畢加索進行處理。 例如:Picasso.with(context).load(url).into(view/*Your image view*/);

+0

你好,非常感謝你的回覆。我通過URL訪問JSON數據,因此我將該特定URL放在load()區域中?我現在正在研究畢加索,以及它如何適用於Android適配器和視圖。你能否詳細說明你提供的畢加索例子?謝謝。 – JohnWilliams

+0

不,你只需要傳遞你在JSON數據中獲取的圖片url。從你的Json數據中獲取所有圖像URL使用for-each循環,並將它們保存到一個List中,然後將這個List傳遞給你的適配器。遵循這個適配器代碼。 https://github.com/square/picasso/blob/master/picasso-sample/src/main/java/com/example/picasso/SampleListDetailAdapter.java 希望這會幫助你! –