gpt4 book ai didi

android - 图片来自网址

转载 作者:行者123 更新时间:2023-11-30 03:40:51 25 4
gpt4 key购买 nike

我开始构建一个游戏,这个游戏从服务器获取图像。

我使用 Bitmap 转换 IMAGE*S*,但它的工作速度很慢。

加载 22 张图片(每张图片 100KB)需要 25 - 40 秒。


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);

附言..

我以前用过 LazyList,但它不是我的目标。

更多优惠?

谢谢....

最佳答案

您正在尝试从 HTTP 连接getInputStream(),同时使用 BitmatpFactory 对其进行解码,以便BitmatpFactory 工厂总是必须等待输入流来收集数据。

而且我没有看到输入流的任何 close() - 期待锡 finally block ,这可能会导致进一步的错误。

试试这个:

  • 在单独的线程中创建 HTTP 连接,以便您可以同时下载图像。

  • 仅在文件下载后解码位图(您可能需要为位图解码器打开另一个流,但它比您当前的解决方案更快更清晰)。

我们还要检查您的连接带宽,以确保您正在做的事情受到这个因素(网络带宽)的限制。

[更新] 这些是一些实用函数:

/**
* 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;
}

关于android - 图片来自网址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15778632/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com