Android 从url加载图像
我有一个图像URL。我想在ImageView中显示此URL中的图像,但我无法这样做 如何做到这一点Android 从url加载图像,android,Android,我有一个图像URL。我想在ImageView中显示此URL中的图像,但我无法这样做 如何做到这一点 import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import android.graphics.Bitmap; import android.g
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
import android.widget.Toast;
public class imageDownload {
Bitmap bmImg;
void downloadfile(String fileurl,ImageView img)
{
URL myfileurl =null;
try
{
myfileurl= new URL(fileurl);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
try
{
HttpURLConnection conn= (HttpURLConnection)myfileurl.openConnection();
conn.setDoInput(true);
conn.connect();
int length = conn.getContentLength();
int[] bitmapData =new int[length];
byte[] bitmapData2 =new byte[length];
InputStream is = conn.getInputStream();
BitmapFactory.Options options = new BitmapFactory.Options();
bmImg = BitmapFactory.decodeStream(is,null,options);
img.setImageBitmap(bmImg);
//dialog.dismiss();
}
catch(IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
// Toast.makeText(PhotoRating.this, "Connection Problem. Try Again.", Toast.LENGTH_SHORT).show();
}
}
}
在你的活动中
拍摄图像查看和设置资源
图像下载(url,yourImageview) 下面是从URL显示图像的示例代码
public static Void downloadfile(String fileurl, ImageView img) {
Bitmap bmImg = null;
URL myfileurl = null;
try {
myfileurl = new URL(fileurl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) myfileurl.openConnection();
conn.setDoInput(true);
conn.connect();
int length = conn.getContentLength();
if (length > 0) {
int[] bitmapData = new int[length];
byte[] bitmapData2 = new byte[length];
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
img.setImageBitmap(bmImg);
}
} catch (IOException e) {
e.printStackTrace();
}
}
如果您是基于按钮单击加载图像,那么上面接受的答案是很好的,但是如果您是在新活动中执行此操作,它会使UI冻结一两秒钟。环顾四周,我发现一个简单的异步任务消除了这个问题 要在活动结束时使用asynctask添加此类,请执行以下操作:
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
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) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
别忘了在清单文件中添加以下权限
<uses-permission android:name="android.permission.INTERNET"/>
对我来说很有用。:) UrlImageViewHelper将使用在URL中找到的图像填充ImageView。UrlImageViewHelper将自动下载、保存和缓存BitmapDrawables中的所有图像URL。重复的URL不会两次加载到内存中。位图内存是通过使用弱引用哈希表来管理的,因此一旦图像不再被您使用,它就会被自动垃圾收集 UrlImageViewHelper.setUrlDrawable(imageView,“http://example.com/image.png"); 给你
void loadImage(String image_location) {
URL imageURL = null;
if (image_location != null) {
try {
imageURL = new URL(image_location);
HttpURLConnection connection = (HttpURLConnection) imageURL
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(inputStream);// Convert to bitmap
ivdpfirst.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
} else {
//set any default
}
}
试试这个:
InputStream input = contentResolver.openInputStream(httpuri);
Bitmap b = BitmapFactory.decodeStream(input, null, options);
试试这个
添加毕加索库jar文件
Picasso.with(context)
.load(ImageURL)
.resize(width,height).noFade().into(imageView);
公共类MainActivity扩展活动{
位图b;
图像视图img;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img=(ImageView)findViewById(R.id.imageView1);
信息信息=新信息();
信息。执行(“”);
}
公共类信息扩展异步任务
{
@凌驾
受保护的字符串doInBackground(字符串…arg0){
尝试
{
URL=新URL(“http://10.119.120.10:80/img.jpg");
InputStream is=new BufferedInputStream(url.openStream());
b=位图工厂.decodeStream(is);
}捕获(例外e){}
返回null;
}
@凌驾
受保护的void onPostExecute(字符串结果){
img.setImageBitmap(b);
}
}
}
基于我自己编写的加载程序
具有加载效果和显示效果:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import java.io.InputStream;
/**
* Created by Sergey Shustikov (pandarium.shustikov@gmail.com) at 2015.
*/
public class DownloadImageTask extends AsyncTask<String, Void, Bitmap>
{
public static final int ANIMATION_DURATION = 250;
private final ImageView mDestination, mFakeForError;
private final String mUrl;
private final ProgressBar mProgressBar;
private Animation.AnimationListener mOutAnimationListener = new Animation.AnimationListener()
{
@Override
public void onAnimationStart(Animation animation)
{
}
@Override
public void onAnimationEnd(Animation animation)
{
mProgressBar.setVisibility(View.GONE);
}
@Override
public void onAnimationRepeat(Animation animation)
{
}
};
private Animation.AnimationListener mInAnimationListener = new Animation.AnimationListener()
{
@Override
public void onAnimationStart(Animation animation)
{
if (isBitmapSet)
mDestination.setVisibility(View.VISIBLE);
else
mFakeForError.setVisibility(View.VISIBLE);
}
@Override
public void onAnimationEnd(Animation animation)
{
}
@Override
public void onAnimationRepeat(Animation animation)
{
}
};
private boolean isBitmapSet;
public DownloadImageTask(Context context, ImageView destination, String url)
{
mDestination = destination;
mUrl = url;
ViewGroup parent = (ViewGroup) destination.getParent();
mFakeForError = new ImageView(context);
destination.setVisibility(View.GONE);
FrameLayout layout = new FrameLayout(context);
mProgressBar = new ProgressBar(context);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER;
mProgressBar.setLayoutParams(params);
FrameLayout.LayoutParams copy = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
copy.gravity = Gravity.CENTER;
copy.width = dpToPx(48);
copy.height = dpToPx(48);
mFakeForError.setLayoutParams(copy);
mFakeForError.setVisibility(View.GONE);
mFakeForError.setImageResource(android.R.drawable.ic_menu_close_clear_cancel);
layout.addView(mProgressBar);
layout.addView(mFakeForError);
mProgressBar.setIndeterminate(true);
parent.addView(layout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
}
protected Bitmap doInBackground(String... urls)
{
String urlDisplay = mUrl;
Bitmap bitmap = null;
try {
InputStream in = new java.net.URL(urlDisplay).openStream();
bitmap = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap result)
{
AlphaAnimation in = new AlphaAnimation(0f, 1f);
AlphaAnimation out = new AlphaAnimation(1f, 0f);
in.setDuration(ANIMATION_DURATION * 2);
out.setDuration(ANIMATION_DURATION);
out.setAnimationListener(mOutAnimationListener);
in.setAnimationListener(mInAnimationListener);
in.setStartOffset(ANIMATION_DURATION);
if (result != null) {
mDestination.setImageBitmap(result);
isBitmapSet = true;
mDestination.startAnimation(in);
} else {
mFakeForError.startAnimation(in);
}
mProgressBar.startAnimation(out);
}
public int dpToPx(int dp) {
DisplayMetrics displayMetrics = mDestination.getContext().getResources().getDisplayMetrics();
int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
return px;
}
}
试试毕加索nice,一句话就完成了
Picasso.with(context)
.load(ImageURL)
.resize(width,height).into(imageView);
教程:
(注意:在最新版本中)我尝试过的最好的方法,而不是使用任何库
public Bitmap getbmpfromURL(String surl){
try {
URL url = new URL(surl);
HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
urlcon.setDoInput(true);
urlcon.connect();
InputStream in = urlcon.getInputStream();
Bitmap mIcon = BitmapFactory.decodeStream(in);
return mIcon;
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
return null;
}
}
对我来说,它是其他图书馆中最好的
只需使用Fresco,然后简单地设置imageURI,如下所示:
draweeView.setImageURI(uri);
查看解释Fresco优点的答案。下面的代码向您展示了如何使用RxAndroid从url字符串设置ImageView。 首先,添加RxAndroid库2.0
dependencies {
// RxAndroid
compile 'io.reactivex.rxjava2:rxandroid:2.0.0'
compile 'io.reactivex.rxjava2:rxjava:2.0.0'
// Utilities
compile 'org.apache.commons:commons-lang3:3.5'
}
现在使用setImageFromUrl设置图像
public void setImageFromUrl(final ImageView imageView, final String urlString) {
Observable.just(urlString)
.filter(new Predicate<String>() {
@Override public boolean test(String url) throws Exception {
return StringUtils.isNotBlank(url);
}
})
.map(new Function<String, Drawable>() {
@Override public Drawable apply(String s) throws Exception {
URL url = null;
try {
url = new URL(s);
return Drawable.createFromStream((InputStream) url.getContent(), "profile");
} catch (final IOException ex) {
return null;
}
}
})
.filter(new Predicate<Drawable>() {
@Override public boolean test(Drawable drawable) throws Exception {
return drawable != null;
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Drawable>() {
@Override public void accept(Drawable drawable) throws Exception {
imageView.setImageDrawable(drawable);
}
});
}
public void setImageFromUrl(最终ImageView ImageView,最终字符串urlString){
可观察的.just(urlString)
.filter(新谓词(){
@重写公共布尔测试(字符串url)引发异常{
返回StringUtils.isNotBlank(url);
}
})
.map(新函数(){
@重写公共可提取应用(字符串s)引发异常{
URL=null;
试一试{
url=新的url;
返回Drawable.createFromStream((InputStream)url.getContent(),“profile”);
}捕获(最终IOEX){
返回null;
}
}
})
.filter(新谓词(){
@重写公共布尔测试(可绘制)引发异常{
返回可提取!=null;
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.订阅(新消费者){
@重写公共void accept(可提取可提取)引发异常{
imageView.setImageDrawable(可绘制);
}
});
}
在清单中添加Internet权限
<uses-permission android:name="android.permission.INTERNET" />
现在将其添加到onCreate方法中
ImageView img_add = (ImageView) findViewById(R.id.img_add);
img_add.setImageBitmap(getBitmapFromURL("http://www.deepanelango.me/wpcontent/uploads/2017/06/noyyal1.jpg"));
这对我很有用。有两种方法: 1)使用Glide library这是从url加载图像的最佳方式,因为当您第二次尝试显示相同的url时,它将从catch中显示,从而提高应用程序性能
Glide.with(context).load("YourUrl").into(imageView);
依赖项:实现'com.github.bumptech.glide:glide:4.10.0'
2)使用流。这里您要从url图像创建位图
URL url = new URL("YourUrl");
Bitmap bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(bitmap);
看这些问题的可能重复,集中在第一个答案上,在这里你可以找到两种简单而完整的方法:或者你可以使用毕加索和Glide图像加载器并显示在ImageView上。我喜欢这个解决方案,你应该只清理onPostExecute的代码,因为它的主体不在。这很好@索菲娅,你说清理是什么意思?如果你的照片数量未知怎么办?@5er我在原始答案中有些括号不正确。我已经清理了它,所以你应该能够按原样使用它。别忘了我们还需要在清单中添加权限:这对于学习/黑客(升级)来说是很棒的,但是对于任何产品,你都应该使用Imageloader库,有很多。我最喜欢的是Universal Image loader、毕加索等。你真的不应该使用它,因为它会阻塞UI线程。此库将为您处理线程和下载:如果您在一个单独的线程上运行该块,减去setImageBitmapits working(我在缩略图中显示)和onclick imageview(我使用的是dsplaying dailog,但它在10secs@koush-如果用
异步任务
包装,则此代码就可以了。您应该创建任何网络在单独的线程中进行操作,加载位图后,可以使用ImageView.post()或Handler.post()毕加索、Glide也是我的最爱。Glide的语句是q
dependencies {
// RxAndroid
compile 'io.reactivex.rxjava2:rxandroid:2.0.0'
compile 'io.reactivex.rxjava2:rxjava:2.0.0'
// Utilities
compile 'org.apache.commons:commons-lang3:3.5'
}
public void setImageFromUrl(final ImageView imageView, final String urlString) {
Observable.just(urlString)
.filter(new Predicate<String>() {
@Override public boolean test(String url) throws Exception {
return StringUtils.isNotBlank(url);
}
})
.map(new Function<String, Drawable>() {
@Override public Drawable apply(String s) throws Exception {
URL url = null;
try {
url = new URL(s);
return Drawable.createFromStream((InputStream) url.getContent(), "profile");
} catch (final IOException ex) {
return null;
}
}
})
.filter(new Predicate<Drawable>() {
@Override public boolean test(Drawable drawable) throws Exception {
return drawable != null;
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Drawable>() {
@Override public void accept(Drawable drawable) throws Exception {
imageView.setImageDrawable(drawable);
}
});
}
<uses-permission android:name="android.permission.INTERNET" />
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;
}
}
ImageView img_add = (ImageView) findViewById(R.id.img_add);
img_add.setImageBitmap(getBitmapFromURL("http://www.deepanelango.me/wpcontent/uploads/2017/06/noyyal1.jpg"));
Glide.with(context).load("YourUrl").into(imageView);
URL url = new URL("YourUrl");
Bitmap bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(bitmap);