如何在安卓中显示来自URL的图片

5
我使用这段代码从URL中显示图像,它能正常工作,但是问题是该图像被存储在设备上,因为我只想在用户连接到互联网时才显示此图像。
ImageView imageView=(ImageView) findViewById(R.id.imageView3);
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(bitmap);

在Android中如何显示来自URL的图片?

你可以在Android中使用Fresco、Volley、UniversalImageLoader或Picasso库。 - Vishal Patoliya ツ
使用Glide。这样更好。 - therealprashant
使用Picasso很容易集成到项目中,基本上只需要一行代码即可运行。 - Abbas
vishal 我使用了 Picasso 但是出现了相同的问题。 - Ridae HAMDANI
使用Glide加载图片。 - pooja
可能是如何在Android上显示来自URL的图像的重复问题。 - jww
9个回答

7
compile "com.squareup.picasso:picasso:2.4.0"

使用这个库来加载图片。
Picasso.with(context)
       .load(url)
       .placeholder(R.drawable.placeholder) //optional
       .resize(imgWidth, imgHeight)         //optional  
       .centerCrop()                        //optional   
       .into(image);                        //Your image view object.

6

尝试这个解决方案...

image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(image);

它会对你有所帮助。


3

Glide库比Picasso更好,我建议你使用Glide

要在Build.gradle文件中的依赖部分执行此操作,请添加以下代码:

compile 'com.github.bumptech.glide:glide:3.7.0'

然后在您想要显示图像的Activity中,在onCreate方法中使用以下代码:

String myUrl = "https://github.com/bumptech/glide/raw/master/static/glide_logo.png";

ImageView imageView = (ImageView)findViewById(R.id.yourImageView);

Glide.with(getApplicationContext())
     .load(myUrl)
     .into(imageView);

你能说一下为什么使用Glide而不是Picasso吗? - UNREAL

1
你可以使用Picasso库将图片加载到imageView中,它很容易使用。
在您的应用级build.gradle文件中添加依赖项 compile 'com.squareup.picasso:picasso:2.5.2' 像这样从url加载图片
Picasso.with(this).load(url).into(imageView);

了解更多有关毕加索的信息点击此处进入链接描述


1
compile已被弃用,请使用implementation代替 =) - xjcl
请注意,into()异步的,因此在其后面放置 marker.showInfoWindow() 并不起作用。 - xjcl

0
我用 Kotlin 最终得到了这样的结果。
//download
val result = lifecycleScope.async(Dispatchers.IO){
    try {
        val url = URL("url")
        return@async BitmapFactory.decodeStream(url.openConnection().getInputStream())
    } catch (e: IOException){
        println("Error")
    } catch (e: UnknownServiceException){
        println("Error2")
    } catch (e: MalformedURLException){
        println("Error3")
    }
}

lifecycleScope.launch {
    val bitmap = result.await() as Bitmap
    val imageView: ImageView = findViewById(R.id.post_image)
    imageView.setImageBitmap(bitmap)  
}

0
Glide.with(context).load(uri).asBitmap().placeholder(R.drawable.yourimage).error(R.drawable.yourimage).into(yourview); 

除了上面的答案,如果图像URL返回null,您可以像上面那样将默认图像加载到视图中。

0
使用以下代码来检查网络连接性:

            ConnectivityManager connectivity = (ConnectivityManager) _Context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connectivity != null) {
            NetworkInfo activeNetwork = connectivity.getActiveNetworkInfo();
            boolean isConnected = activeNetwork != null &&
                    activeNetwork.isConnectedOrConnecting();
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        available = true;
                    }
                }
            }
        }
        if (available == false) {
            NetworkInfo wiMax = connectivity.getNetworkInfo(6);
            if (wiMax != null && wiMax.isConnected()) {
                available = true;
            }
        }

然后使用它来下载图像

class DownloadTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
String image_name, studentName;
TextDrawable drawable;

public DownloadTask(ImageView bmImage, String file_name) {
    this.bmImage = bmImage;
    this.image_name = file_name;
}

protected Bitmap doInBackground(String... urls) {
    InputStream input = new java.net.URL(image_name).openStream();
    if(input.available()!=0) {
        return BitmapFactory.decodeStream(input);
    }
    return null;
}

protected void onPostExecute(Bitmap result) {
    try {
        if(result == null)
            bmImage.setImageDrawable(drawable);
        else
        bmImage.setImageBitmap(result);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

这将在设备中存储图像。 - Vivek Mishra
但我想要将文件存储在设备中。 - Ridae HAMDANI

0

我也遇到了同样的问题,使用以下代码解决了。

Picasso.with(context).load(uri).networkPolicy(NetworkPolicy.NO_CACHE)
        .memoryPolicy(MemoryPolicy.NO_CACHE)
        .placeholder(R.drawable.bv_logo_default)
        .into(viewImage_imageView);

0

也可以尝试这个,根据您的需要调整大小,或者使用通用加载器进行调整

<ImageView
android:id="@id/ivImage"
android:layout_width="150dp"
android:layout_height="150dp"
android:adjustViewBounds="true"

android:scaleType="fitCenter" />

使用Android通用图像加载器

声明

    private ImageLoader imageLoader1;

On Create

 imageLoader1 = ImageLoader.getInstance();

 imageLoader1.init(ImageLoaderConfiguration.createDefault(youractivity.this));

这里的no_image是一个可绘制的图像,但没有任何图像加载到缓存中。
   DisplayImageOptions
            options = new DisplayImageOptions.Builder()
            .cacheInMemory(true)
            .cacheOnDisk(true)
            .showImageOnLoading(R.drawable.no_image) // resource or drawable
            .showImageForEmptyUri(R.drawable.no_image) // resource or drawable
            .showImageOnFail(R.drawable.no_image)
            .considerExifParams(true)
            .bitmapConfig(Bitmap.Config.RGB_565)
            .build();

    imageLoader1.displayImage(yourpathURl.replace(" ", "%20"), ivImage, options);

还需要添加Gradle依赖项...下载通用加载器的最新jar包

jar包的下载链接

  compile files('libs/universal-image-loader-1.9.5-with-sources.jar')

你也可以使用Piccaso和Glide


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接