title: Decoding a jpeg in Android
body: <p>I have JSON data that I am viewing from a URL. There are many JSON objects in the JSON array, one of which is a jpeg image. </p>
  
  <p>I would like to send that image to a listview in an Android app.</p>
  
  <p>Right now I have the image JSON object linked to a private static final String TAG in my Java file. However, I realize that I must decode the image or I will receive an error of: Unable to decode stream: java.io.FileNotFoundException and resolveUri failed on bad bitmap uri.</p>
  
  <p>I am in a long and ongoing search to understand how to decode the JSON jpeg image, much of such research taken place by viewing posts on this website so please do not mark as a duplicate question.</p>
  
  <pre><code>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&lt;HashMap&lt;String, Object&gt;&gt;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&lt;?&gt; 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&lt;NameValuePair&gt; 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&lt;Void, Void, Void&gt; {
  
          @Override
          protected void onPreExecute() {
              super.onPreExecute();
             caridList = new ArrayList&lt;HashMap&lt;String, Object&gt;&gt;();
  
              //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: ", "&gt; " + 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 &lt; 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&lt;String, Object&gt; matchGetCars = new HashMap&lt;String, Object&gt;();
  
                                  //Adds each child node to HashMap key =&gt; 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());
                  }
      }
  </code></pre>
  
  <p>So any suggestions of how to decode a JSON jpeg image would be greatly appreciated. Thank you.  </p>
  
  <pre><code>}
  </code></pre>
  
  <p>Update:</p>
  
  <pre><code> 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 &gt; 0 &amp;&amp;  i &lt; 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&lt;Void, Void, Void&gt; {
  
          @Override
          protected void onPreExecute() {
              super.onPreExecute();
              caridList = new ArrayList&lt;HashMap&lt;String, Object&gt;&gt;();
  
              //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: ", "&gt; " + 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 &lt; 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&lt;String, Object&gt; matchGetCars = new HashMap&lt;String, Object&gt;();
  
                          //Adds each child node to HashMap key =&gt; 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());
  
          }
  
      }
  </code></pre>
  
  <p>Logcat:</p>
  
  <pre><code>V/List parsed﹕ [{CarMainImage=/images/image.php?w=200&amp;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....
  </code></pre>
  
  <p>I do not understand why the parsed list is correctly logged and then those to error pop up. However, the JSON jpeg in the URL is not fully formatted like the jpeg in the log cat because the jpeg in JSON looks like: /images/image.php?w=200... and the jpeg in logcat looks like: /images/image.php?200.. So the difference is the ..can anyone elaborate if that could why the error messages are shown and/or offer suggestions to fix the errors?
  I am very willing to research and go back and forth to understand anything that you suggest. Thanks.</p>