从url中采样位图

时间:2014-06-08 18:46:36

标签: android

我正在尝试从网址中减少位图的大小。我看到很多帖子,但都是关于对本地文件进行采样。我想在网址上对图片进行采样。这是我的代码:

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

这种做法是否正确?我在这个功能的应用程序中出现了内存崩溃问题。有什么想法吗?

2 个答案:

答案 0 :(得分:6)

这很有效。我在http://blog.vandzi.com/2013/01/get-scaled-image-from-url-in-android.html找到了它。使用以下代码片段,根据需要传递params。

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

它非常灵活......我认为你应该尝试一下。

答案 1 :(得分:2)

你错了。你要求将图片大10倍:)你应该用正常数字给出命令,而不是分数。例如:

    final BitmapFactory.Options options2 = new BitmapFactory.Options();
    options2.inSampleSize = 8;
    b = BitmapFactory.decodeFile(image, options2);

使用此配置,您可以获得比原始图像小8倍的图片。

更新:要从互联网加载this类图像,请执行以下操作:

ImageLoader loader = new ImageLoader(context);
Bitmap image = loader.getBitmap(URL);