缩放后位图颜色代码更改

时间:2017-11-29 10:26:12

标签: android colors bitmap

我有一张图片的颜色代码为#AAA28B(170R,162G,139B)。现在让我们说现在的图像尺寸是1200x1200我想让它缩小到600x600所以我使用下面的代码并得到位图,但问题是它的位图颜色代码更改为#ABA38C,所以它的RGB值增加到加一比较到原始图像颜色并成为(171R,163G,140B)如何防止这种情况?。

请参阅附上截图,其中第一张图片如果原版直接从android drawable加载,则使用以下代码加载。

private void loadImage(int width, int height){

        Bitmap bitMapTest=BitmapFactory.decodeResource(getResources(),R.drawable.ic_test);

        Log.i("IMAGE","Image format is"+ bitMapTest.getConfig().name()+
                "Image size is"+ bitMapTest.hasAlpha() + "bitmap size is"+ bitMapTest.getHeight());


        Bitmap decodeBitmap=decodeSampledBitmapFromResource(getResources(),R.drawable.ic_test,width,height);
        Log.i("IMAGE","Image format is"+ decodeBitmap.getConfig().name()+
                "Image size is"+ decodeBitmap.hasAlpha() + "bitmap size is"+ decodeBitmap.getHeight());

         //adjust of alha deos not give me any help result remain same
        //decodeBitmap=adjustOpacity(decodeBitmap);

        mImgView.setImageBitmap(decodeBitmap);

    }

    public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
                                                         int reqWidth, int reqHeight) {

        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        options.inPreferredConfig= Bitmap.Config.ARGB_8888;
        options.inScaled=false;
        BitmapFactory.decodeResource(res, resId, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(res, resId, options);
    }

    public 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 = 2;

        if (height > reqHeight || width > reqWidth) {

            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            // Calculate the largest inSampleSize value that is a power of 2 and keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) >= reqHeight
                    && (halfWidth / inSampleSize) >= reqWidth) {
                inSampleSize *= 2;
            }
        }

        return inSampleSize;
    }

这是原始图像: -

Here is solid color image which i need to scale down

1 个答案:

答案 0 :(得分:0)

对于像this这样的实体图像,似乎应用以下代码来实现缩小工作。

Bitmap  decodeBitmap=Bitmap.createScaledBitmap(sourceBitmap,width,height,false/*Make sure filter is false*/);