在 Android 中解码 jpeg

Decoding a jpeg in Android

我有 JSON 数据,我正在查看来自 URL 的数据。 JSON 数组中有许多 JSON 个对象,其中一个是 jpeg 图片。

我想将该图像发送到 Android 应用程序中的列表视图。

现在我的 Java 文件中有图像 JSON 对象链接到私有静态最终字符串标记。但是,我意识到我必须解码图像,否则我会收到以下错误:无法解码流: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 格式并不像 log cat 中的 jpeg 那样完全格式化,因为 JSON 中的 jpeg 看起来像:/images/image.php ?w=200... 并且 logcat 中的 jpeg 看起来像:/images/image.php?200.. 所以区别在于 .. 任何人都可以详细说明是否会出现错误已显示消息 and/or 提供修复错误的建议? 我非常愿意研究并来回了解您的建议。谢谢。

有哪种 BitmapFactory 方法适合您?有一对可以接受一个字节数组并给你一个 Bitmap。然后你可以很容易地把你的Bitmap变成ImageView

我建议使用 Picasso

因为您只需要在适配器的 getView() 函数中提供图像 url 和 imageView。从 url 下载图像到位图转换并设置为图像视图的所有工作都将由 Picasso 处理。 例如:Picasso.with(context).load(url).into(view/*Your image view*/);

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;
          }
        //-----------------------