zoukankan      html  css  js  c++  java
  • android:通过URL加载ImageView

    iphone上实现很简单,一行代码:

    imageView.image =[UIImage imageWithContentsOfURL:theURL];

    android:

    两种方法:

    Bitmap bimage=  getBitmapFromURL(bannerpath);
    image.setImageBitmap(bimage);
    
     public static Bitmap getBitmapFromURL(String src) {
            try {
                Log.e("src",src);
                URL url = new URL(src);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);
                connection.connect();
                InputStream input = connection.getInputStream();
                Bitmap myBitmap = BitmapFactory.decodeStream(input);
                Log.e("Bitmap","returned");
                return myBitmap;
            } catch (IOException e) {
                e.printStackTrace();
                Log.e("Exception",e.getMessage());
                return null;
            }
        }

    or try it

    public static Bitmap loadBitmap(String url) {
        Bitmap bitmap = null;
        InputStream in = null;
        BufferedOutputStream out = null;
    
        try {
            in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
    
            final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
            out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
            copy(in, out);
            out.flush();
    
            final byte[] data = dataStream.toByteArray();
            BitmapFactory.Options options = new BitmapFactory.Options();
            //options.inSampleSize = 1;
    
            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
        } catch (IOException e) {
            Log.e(TAG, "Could not load Bitmap from: " + url);
        } finally {
            closeStream(in);
            closeStream(out);
        }
    
        return bitmap;
    }

     

    方法2

     

        Drawable drawable = LoadImageFromWebOperations(bannerpath);
        image.setImageDrawable(drawable);
    
         private Drawable LoadImageFromWebOperations(String url)
        {
             try
             {
                 InputStream is = (InputStream) new URL(url).getContent();
                 Drawable d = Drawable.createFromStream(is, "src name");
                 return d;
             }catch (Exception e) {
                 System.out.println("Exc="+e);
                 return null;
             }
         }

     

    搞定!

     

  • 相关阅读:
    [Java入门] 从键盘输入两个整数,求最小公倍数并输出
    【C#食谱】【面食】菜单3:用泛型替代ArrayList
    C# Stable Sort(稳固排序)
    【C#食谱】【面食】菜单4:List和LinkedList性能比较
    一个非常酷的应用:修改“开始”菜单的显示文本
    我的第一个5年计划
    C#语言重要常识
    决定执行力的49个细节
    .NET资源链接
    标准表达式中数据类型不匹配(Access 时间格式)
  • 原文地址:https://www.cnblogs.com/mybkn/p/2515913.html
Copyright © 2011-2022 走看看