我开始构建游戏,这个游戏从服务器获取图像。
我使用Bitmap转换IMAGE * S *并且其工作缓慢。
需要25到40秒才能加载22张图像(每张图像100张)。
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
实现:
Bitmap pictureBitmap = ImageFromUrl.getBitmapFromURL(path);
PS ..
之前我使用过LazyList,这不符合我的目标。
更多优惠?
... TNX
答案 0 :(得分:1)
您在使用 getInputStream()
对其进行解码时,尝试从HTTP连接 BitmatpFactory
,以便BitmatpFactory
工厂始终拥有等待输入流收集数据。
我没有看到任何close()
输入流 - 期待锡finally
阻止,这可能会导致更多错误。
试试这个:
在分离的线程中创建HTTP连接,以便您可以同时下载图像。
仅在下载文件后解码位图(您可能必须为位图解码器打开另一个流,但它比您当前的解决方案更快更清晰)。
还可以检查您的连接带宽,以确保您正在做的事情受此因素(网络带宽)的限制。
[更新]这些是一些util函数:
/**
* Util to download data from an Url and save into a file
* @param url
* @param outFilePath
*/
public static void HttpDownloadFromUrl(final String url, final String outFilePath)
{
try
{
HttpURLConnection connection = (HttpURLConnection) (new URL(url)).openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();
FileOutputStream outFile = new FileOutputStream(outFilePath, false);
InputStream in = connection.getInputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = in.read(buffer)) > 0)
{
outFile.write(buffer, 0, len);
}
outFile.close();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
/**
* Spawn a thread to download from an url and save into a file
* @param url
* @param outFilePath
* @return
* The created thread, which is already started. may use to control the downloading thread.
*/
public static Thread HttpDownloadThreadStart(final String url, final String outFilePath)
{
Thread clientThread = new Thread(new Runnable()
{
@Override
public void run()
{
HttpDownloadFromUrl(url, outFilePath);
}
});
clientThread.start();
return clientThread;
}