【问题标题】:android using async http connection to get image bitmapandroid使用异步http连接获取图像位图
【发布时间】:2011-12-28 20:28:25
【问题描述】:

我正在尝试使用异步请求从 url 中获取图像,以防止 url 挂起。这是我正在使用的这段代码

private void setImg(final ImageView im, String url){
    AsyncHttpClient client = new AsyncHttpClient();
    client.get(url, new AsyncHttpResponseHandler(){
        public void onSuccess(String response){
            try{
                byte[] imageAsBytes = response.getBytes();
                im.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length));
                im.refreshDrawableState();
            } catch(Throwable e){
                e.printStackTrace();
            }
        }
    });
}

这总是在 logcat 中显示这个警告

12-29 01:55:33.043: D/skia(14414): --- SkImageDecoder::Factory returned null

我找不到合适的理由。有什么帮助吗?

【问题讨论】:

  • 鉴于 Android 已经提供了一切方便的东西(HttpClient 和 AsyncTask)并且实现起来非常简单,创建/使用这个额外的第三方库 AsyncHttpClient 的意义何在。通过这样做,您将自己的应用程序置于依赖于其他人工作的风险中,您知道他们维护他们的项目的情况吗?自己做吧。
  • 它是一个积极维护的项目,它为我提供了很多能力,这将花费我很多时间从头开始。
  • 您是否检查过 1) 您检索的字节实际上代表一个图像(而不是例如一些未解析的重定向或 html 内容),以及 2) 您没有尝试读取内容(通常是 InputStream ) 你的 AsyncHttpClient 中的 http 响应两次?
  • 1. onSucess 是什么意思?完全响应,完全到达还是仅 200 行?如果只有 200 ok,你的 http 客户端是否还有其他回调给你额外的字节? 2.您可以尝试将字节写入磁盘并使用十六进制编辑器将它们与您将使用 curl 等下载的图像进行比较吗? 3. 会不会是图片太大了,你应该在解析时使用'Options' clss 让它变小?

标签: android bitmap android-asynctask android-imageview


【解决方案1】:

现在已经向 AsyncHttp 添加了二进制响应处理程序,您可以简单地使用 androids BitmapFactory.decodeByeArray 函数:

AsyncHttpClient client = new AsyncHttpClient();
client.get(image_url, null, new AsyncHttpResponseHandler() {            
    @Override
    public void onSuccess(byte[] fileData) {
        Bitmap image = BitmapFactory.decodeByteArray(fileData, 0, fileData.length);
        //Do whatever you want with the image variable    
    }
});

【讨论】:

  • onSuccess(byte[] fileData) 不会覆盖超类型中的任何方法。这不起作用,并且会使您的应用程序崩溃!
  • @CristyYG 我通过更新到 AsyncHttpClient loopj.com/android-async-http987654321@ 的 1.4.9 版解决了我的问题
【解决方案2】:

我最近一直在使用以下库:UrlImageViewHelper。它使用 AsyncTask 来下载图像。您的代码将是这样的:

private void setImg(final ImageView im, String url){
    UrlImageViewHelper.setUrlDrawable(im, url) ;
}

现在很简单,对吗?

【讨论】:

    【解决方案3】:

    如果有人还在做这个,我就是这样做的

    public static void setImg(final ImageView im, final String url){
        AsyncTask<Void, Void, Bitmap> t = new AsyncTask<Void, Void, Bitmap>(){
            protected Bitmap doInBackground(Void... p) {
                Bitmap bm = null;
                try {
                    URL aURL = new URL(url);
                    URLConnection conn = aURL.openConnection();
                    conn.setUseCaches(true);
                    conn.connect(); 
                    InputStream is = conn.getInputStream(); 
                    BufferedInputStream bis = new BufferedInputStream(is); 
                    bm = BitmapFactory.decodeStream(bis);
                    bis.close(); 
                    is.close();
                } catch (IOException e) { 
                    e.printStackTrace(); 
                }
                return bm;
            }
    
            protected void onPostExecute(Bitmap bm){
                Bitmap output = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), Config.ARGB_8888);
                Canvas canvas = new Canvas(output);
    
                final int color = 0xff424242;
                final Paint paint = new Paint();
                final Rect rect = new Rect(0, 0, bm.getWidth(), bm.getHeight());
                final RectF rectF = new RectF(rect);
                final float roundPx = 5;
    
                paint.setAntiAlias(true);
                canvas.drawARGB(0, 0, 0, 0);
                paint.setColor(color);
                canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
    
                paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
                canvas.drawBitmap(bm, rect, rect, paint);
                im.setImageBitmap(output);
            }
        };
        t.execute();
    }
    

    【讨论】:

      【解决方案4】:

      [更新] 图像(和任何二进制数据)响应处理已添加到 loopj 的 android-async-http 库。使用 BinaryHttpResponseHandler

      [旧帖] loopj 的 AsyncHttpClient 还不支持处理 byte[] 响应。有一个叉子可以,但它是一团糟。所以答案是其中之一:

      A1) 你没有。

      A2)您使用通过此链接提供的分叉:https://github.com/loopj/android-async-http/issues/8

      A3)你 fork AsyncHttpClient,添加 byte[] 处理(没有撕掉字符串响应处理,天哪!),然后将其提交回项目。通过这样做,您还将获得开源业力积分。

      【讨论】:

        【解决方案5】:

        Android 使用异步 http 连接获取图像和文本并显示在 listView 中

        public class MainActivity extends Activity {
            ListView list;
            public String IPadd = "http://api.gifts.com/v2/search/product.json?category=Nur&api_key=fd2ut5evb9jgzerjkeph54pz";
        
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
                list=(ListView) findViewById(R.id.listView1);
                new AsyTask().execute(IPadd);
            }
        
            private class AsyTask extends AsyncTask<String, Void, String> {
        
                @Override
                protected String doInBackground(String... url) {
                    HttpClient httpClient = new DefaultHttpClient();
                    HttpGet httpGet = new HttpGet(url[0]);
                    // HttpPost httpPost=new HttpPost(url[0]);
                    String text = null;
                    try {
                        HttpResponse response = httpClient.execute(httpGet);
                        text = EntityUtils.toString(response.getEntity());
        
                    } catch (Exception e) {
                        return e.getLocalizedMessage();
                    }
        
                    return text;
                }
        
                @Override
                protected void onPostExecute(String result) {
                    try {
                        JSONObject jObject = new JSONObject(result);
                        JSONArray jarray = jObject.getJSONArray("products");
                        for (int i = 0; i < jarray.length(); i++) {
                            ProductInfo p=new ProductInfo();
                            JSONObject jObj = jarray.getJSONObject(i);
                            p.setTitle(jObj.getString("title"));
                            p.setId(jObj.getString("price"));
                            p.setImage(jObj.getString("largeProductImageUrl"));
                            ProductInfo.arrayList.add(p);
                        }
                        ArrAdapter adapter=new ArrAdapter(getApplicationContext(),ProductInfo.arrayList);
                        list.setAdapter(adapter);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
        
                }
        
            }
        }
        
            public class ArrAdapter extends BaseAdapter{
        
            TextView id,title;
            ImageView img;
            Context context;
            static ArrayList<ProductInfo> listitem=new ArrayList<ProductInfo>();
            public ArrAdapter(Context applicationContext,ArrayList<ProductInfo> arrayList) {
                this.context=applicationContext;
                listitem=arrayList;
            }
        
            @Override
            public int getCount() {
                return listitem.size();
            }
        
            @Override
            public Object getItem(int position) {
                return listitem.get(position);
            }
        
            @Override
            public long getItemId(int position) {
                return position;
            }
        
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                ProductInfo p=listitem.get(position);
                if(convertView==null)
                {
                    LayoutInflater inflater=(LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
                    convertView=inflater.inflate(R.layout.custom, null);
                }
                id=(TextView) convertView.findViewById(R.id.textView1);
                id.setText(p.getId());
                title=(TextView) convertView.findViewById(R.id.textView2);
                title.setText(p.getTitle());
                img=(ImageView) convertView.findViewById(R.id.imageView1);
                ImageLoader imageloader=new ImageLoader(img);
                imageloader.execute(p.getImage());
                return convertView;
            }
        
        }
        
            public class ProductInfo {
            String ID,title,image;
            static ArrayList<ProductInfo> arrayList=new ArrayList<ProductInfo>();
            public void setId(String id)
            {
                this.ID=id; 
            }
            public String getId()
            {
                return ID;
            }
            public void setTitle(String tit)
            {
                this.title=tit; 
            }
            public String getTitle()
            {
                return title;
            }
            public void setImage(String img)
            {
                this.image=img; 
            }
            public String getImage()
            {
                return image;
            }
        
        }
        
            class  ImageLoader extends AsyncTask<String, Void, Bitmap> {
            ImageView bmImage;
        
            public ImageLoader(ImageView bmImage) {
                this.bmImage = bmImage;
            }
        
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
        
            }
        
            protected Bitmap doInBackground(String... urls) {
                String urldisplay = urls[0];
                Bitmap mIcon11 = null;
                try {
                  InputStream in = new java.net.URL(urldisplay).openStream();
                  mIcon11 = BitmapFactory.decodeStream(in);
                } catch (Exception e) {
        
                }
                return mIcon11;
            }
        
            @Override 
            protected void onPostExecute(Bitmap result) {
                super.onPostExecute(result);
        
                bmImage.setImageBitmap(result);
             }
            }
        

        【讨论】:

          猜你喜欢
          • 2018-03-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-11-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多