在Android上从服务器加载大图像

Bri*_*ian 6 android bitmap imageview

我试图将服务器中的jpg文件显示为imageView.当我尝试加载较小的图像(300x400)时,没有问题.但是当我尝试加载全尺寸图片(2336x3504)时,图像将无法加载.图像的文件大小仅为2mb.我没有在logcat中得到任何错误,也没有抛出异常.它根本不会加载图像.我也试过用这个:

BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap preview_bitmap=BitmapFactory.decodeStream(is,null,options);
Run Code Online (Sandbox Code Playgroud)

这对于加载大文件没有任何帮助,但它确实调整了较小的图像(就像它假设的那样).我确实将大图添加到我的资源并测试它,就像它嵌入在应用程序中一样,它工作正常,只是无法在服务器上工作.我一整天都在工作,似乎无法弄清楚如何加载这些大图片.任何人都可以帮我解决这个问题吗?谢谢你的任何信息.

是我找到上面代码的链接,并且一直在玩其他示例,但仍然没有让它工作.

编辑:

这是我正在使用的代码,用于加载图像:

public static Bitmap getBitmapFromURL(String src) {
    Bitmap bmImg;
    URL myFileUrl = null;

    try {
        myFileUrl = new URL(src);

        HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
        conn.setDoInput(true);
        conn.connect();
        InputStream is = conn.getInputStream();

        BitmapFactory.Options options=new BitmapFactory.Options();
        options.inSampleSize = 16;

        bmImg = BitmapFactory.decodeStream(is, null, options);
        return bmImg;
    } catch (Exception e) {
        // TODO Auto-generated catch block
        Log.d("Error", e.toString());
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是logcat截图(无法弄清楚如何在eclipse中正确复制文本)我在点击按钮加载图像之前清除了日志.所以你看到的就是当我点击那个按钮时会发生什么.我删除了公司和应用程序名称(你看到"com.",假设它的"com.mycompany.myapp". Logcat截图

Dev*_*red 8

当您将其直接连接到远程连接时BitmapFactory.decodeFromStream(),放弃并返回的情况并不少见.在内部,如果你没有提供方法,它会将提供的流包装在一个缓冲区大小为16384的流中.有时可行的一个选项是传递一个更大的缓冲区大小,如:nullInputStreamBufferedInputStreamBufferedInputStream

BufferedInputStream bis = new BufferedInputStream(is, 32 * 1024);
Run Code Online (Sandbox Code Playgroud)

一种更普遍有效的方法是首先完全下载文件,然后解码数据,如下所示:

InputStream is = connection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is, 8190);

ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
    baf.append((byte)current);
}
byte[] imageData = baf.toByteArray();
BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
Run Code Online (Sandbox Code Playgroud)

仅供参考,本例中的缓冲区大小有些随意.正如在其他答案中所说的那样,不要将图像在内存中保留的时间长于你所需要的,这是一个奇妙的想法.您可以考虑将其直接写入文件并显示缩减采样版本.

希望有所帮助!