【问题标题】:How to scale bitmap with high quality and without crash in android如何在android中以高质量和不崩溃的方式缩放位图
【发布时间】:2011-10-06 02:11:35
【问题描述】:

我正在使用 url 下载图像,但缩放后它崩溃并且缩放不正确。 这是我用过的代码,

//Code to fetch bitmap  
Bitmap bmp=HttpFetch.fetchBitmap(imageUrl);

//Scale bitmap

Bitmap myBitmap = getResizedBitmap(bmp, viewWidth, viewHeight);  

public static Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight) {

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;

        int srcWidth = bm.getWidth();
        int srcHeight = bm.getHeight();

        int desiredWidth = newWidth;
        int desiredHeight = newHeight;

        int inSampleSize = 1;
        while(srcWidth / 2 > desiredWidth){
            srcWidth /= 2;
            srcHeight /= 2;
            inSampleSize *= 2;
        }

        float desiredWidthScale = (float) desiredWidth / srcWidth;
        float desiredHeightScale = (float) desiredHeight / srcHeight;

        // Decode with inSampleSize
        options.inJustDecodeBounds = false;
        options.inDither = false;
        options.inSampleSize = inSampleSize;
        options.inScaled = false;
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;

        Matrix matrix = new Matrix();
        matrix.postScale(desiredWidthScale, desiredHeightScale);
        original = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
        return original;
}

找不到使用位图获取 BitmapFactory.Option 的代码,并且大多数地方都使用文件名,是否可以使用位图获取 BitmapFactory.Options?

当我们从网络下载时,请提出更好的解决方案来缩放位图。

【问题讨论】:

  • 您在 Logcat 中遇到了什么错误...?
  • 我没有在 logcat 中观察到任何错误,对于某些图像来说它没有正确发生,并且有时也会崩溃,并非总是如此。对我来说,主要问题是如何获取从网络下载的位图的 BitmapFactory.Options。
  • 您可以尝试使用 Bitmap.createScaledBitmap 代替 Bitmap.createBitmap

标签: android bitmap scaling


【解决方案1】:
original = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);

此行返回一个不可变的Bitmap,调用getResizedBitmap()后,如果你试图修改这个Bitmap,可能会导致崩溃。

Android#createBitmap()

详情请查阅 LogCat。

【讨论】:

    猜你喜欢
    • 2013-01-11
    • 2014-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多