android - 从 url 采样位图

标签 android

我正在尝试减少 url 中位图的大小。我看了很多帖子,但都是关于对本地文件进行采样的。我想在 url 处对图像进行采样。这是我的代码:

public Bitmap getScaledFromUrl(String url) {
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bmOptions.inSampleSize = 1 / 10;
    try {
        return BitmapFactory.decodeStream((InputStream) new URL(url)
                .getContent());
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

这种方法是否正确?使用此功能时,我的应用程序出现内存崩溃。有什么想法吗?

最佳答案

这行得通。我在 http://blog.vandzi.com/2013/01/get-scaled-image-from-url-in-android.html 找到了它.使用以下代码 fragment ,根据需要传递参数。

private static Bitmap getScaledBitmapFromUrl(String imageUrl, int requiredWidth, int requiredHeight) throws IOException {
    URL url = new URL(imageUrl);
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(url.openConnection().getInputStream(), null, options);
    options.inSampleSize = calculateInSampleSize(options, requiredWidth, requiredHeight);
    options.inJustDecodeBounds = false;
    //don't use same inputstream object as in decodestream above. It will not work because 
    //decode stream edit input stream. So if you create 
    //InputStream is =url.openConnection().getInputStream(); and you use this in  decodeStream
    //above and bellow it will not work!
    Bitmap bm = BitmapFactory.decodeStream(url.openConnection().getInputStream(), null, options);
    return bm;
}

private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {
        if (width > height) {
            inSampleSize = Math.round((float) height / (float) reqHeight);
        } else {
            inSampleSize = Math.round((float) width / (float) reqWidth);
        }
    }
    return inSampleSize;
}

它真的很灵活..我认为你应该尝试一下。

关于android - 从 url 采样位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24109600/

相关文章:

android - 在android imageview中旋转缩放拖动图像

android - 位置服务 onProviderEnabled 从未调用过

android - Google 日历 API 中的 "Year 2038 _problem"(Android 应用程序)

php - 尝试制作 Android 服务

android - Python 引发 SyntaxError

android - 如何在多列sqlite数据库上过滤多个数据

java - Android 应用程序在转而使用 java 创建布局后停止工作

android - Libgdx 或原生的

android - 如何统计外部存储文件夹中的文件数?

java - 如何将scrollTo()与Spinner一起使用?