我试图在我的应用中显示来自网址的图片。但是我使用的方式很长。 这个代码我建立在stackoverflow上
public Bitmap getImage(String url,String src_name) throws java.net.MalformedURLException, java.io.IOException {
Bitmap bitmap;
HttpURLConnection connection = (HttpURLConnection)new URL(url) .openConnection();
connection.setRequestProperty("User-agent","Mozilla/4.0");
connection.connect();
InputStream input= connection.getInputStream();
bitmap = BitmapFactory.decodeStream(input);
return bitmap;
}
在10-12秒内加载10张图像。如果使用此代码。
和
///==========================================================================================================================================
public Drawable getImage(String url, String src_name) throws java.net.MalformedURLException, java.io.IOException
{
Drawable abc =Drawable.createFromStream(((java.io.InputStream)new java.net.URL(url).getContent()), src_name);
return abc;
}
如果使用此代码 - 图像在9-11秒内加载。
图像不大。最大宽度或高度为400-450。
我在循环中告诉这个函数是这样的:for (int i =0;i<10;i++){image[i]=getImage(url);}
可以告诉我如何在我的应用程序中最好地和紧固显示图像吗?
亲爱的,彼得。
答案 0 :(得分:1)
您无法取消下载和解码图像所需的时间。数字“10”只是图像质量的函数,您只能尝试优化此数字。
如果服务器由您管理,您可能需要花一些时间根据UI要求优化可下载图像的大小。也尝试延迟加载(我希望你不在UI线程上执行这些操作)。许多次讨论了懒惰下载和延迟解码的许多解决方案:http://www.google.com.sg/search?q=android+images+lazy+load&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a
旁注:不鼓励使用HttpURLConnection
。使用HttpClient
。这也可能会影响性能。看看http://lukencode.com/2010/04/27/calling-web-services-in-android-using-httpclient/
答案 1 :(得分:0)
public static Bitmap getBitmapFromUrl(String url) {
Bitmap bitmap = null;
HttpGet httpRequest = null;
httpRequest = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = null;
try {
response = (HttpResponse) httpclient.execute(httpRequest);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (response != null) {
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = null;
try {
bufHttpEntity = new BufferedHttpEntity(entity);
} catch (IOException e) {
e.printStackTrace();
}
InputStream instream = null;
try {
instream = bufHttpEntity.getContent();
} catch (IOException e) {
e.printStackTrace();
}
bitmap = BitmapFactory.decodeStream(instream);
}
return bitmap;
}
答案 2 :(得分:0)
public static Bitmap decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
Bitmap bitmap = BitmapFactory.decodeFile(filePath, o2);
return bitmap;
}