安卓:位图向下扩展低质量 [英] Android: bitmap down scaling low quality

查看:148
本文介绍了安卓:位图向下扩展低质量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我缩减了一些位图和越来越低质量的结果。我尝试了位图#createScaledBitmap和画布#drawBitmap方法。设置在第一和第二的Paint对象的过滤器旗滤波器参数没有表现出明显的差异。

我试图成立于这些问题的解决方案:

<一个href="http://stackoverflow.com/questions/4821488/bad-image-quality-after-resizing-scaling-bitmap">Bad调整后的图像质量/缩放位

<一个href="http://stackoverflow.com/questions/4231817/quality-problems-when-resizing-an-image-at-runtime">Quality调整问题在运行时图像时

<一个href="http://stackoverflow.com/questions/6087019/drawing-scaled-bitmaps-on-a-surfaceview-no-antialiasing">Drawing在SurfaceView缩放位图 - 无抗锯齿

和其他一些人。

正如有人所说的地方,在createScaledBitmap或在画图对象过滤器标志使双三次插值算法。但是,这都没有区别。使用GIMP立方的,这实际上是双三次,所得到的图像比机器人实现好得多。

下面API级别为19。

解决方案
  

试试这个。

 私人位图performResize(位图位图,诠释requiredWidth,
            INT requiredHeight){
        INT ImageWidth等= bitmap.getWidth();
        INT imageHeight = bitmap.getHeight();
        浮differenceWidth = requiredWidth  -  ImageWidth等;
        浮动比例= differenceWidth / ImageWidth等* 100;
        浮estimatedheight = imageHeight +(百分比* imageHeight / 100);
        浮estimatedwidth = requiredWidth;

        如果(estimatedheight&LT; requiredHeight){
            浮动incresePercentage =(浮点)(requiredHeight  -  estimatedheight);
            百分比+ =(incresePercentage / imageHeight * 100);
            estimatedheight = imageHeight +(百分比* imageHeight / 100);
            estimatedwidth = ImageWidth等+(百分比* ImageWidth等/ 100);
        }

        位= ScalingUtilities.performResize(位图,(INT)estimatedheight,
                (中间体)estimatedwidth);

        如果(bitmap.getHeight()&LT; requiredHeight)//如果计算高度
                                                    //越小则所需
                                                    // 高度
        {
        } 其他 {
            INT xCropPosition =(int)的((bitmap.getWidth() -  requiredWidth)/ 2);
            INT yCropPosition =(int)的((bitmap.getHeight() -  requiredHeight)/ 2);

            位= Bitmap.createBitmap(位图,xCropPosition,yCropPosition,
                    (INT)requiredWidth,(int)的requiredHeight);
        }
        返回的位图;
    }
 

  

实用程序文件

 进口android.content.Context;
进口android.content.res.Resources;
进口android.graphics.Bitmap;
进口android.graphics.Bitmap.Config;
进口android.graphics.BitmapFactory;
进口android.graphics.BitmapFactory.Options;
进口android.graphics.Canvas;
进口android.graphics.Paint;
进口android.graphics.Rect;
进口android.util.DisplayMetrics;
进口android.util.Log;

/ **
 *包含类的位图解码和缩放静态实用方法
 *
 * @author安德烈亚斯Agvard(andreas.agvard@sonyericsson.com)
 * /
公共类ScalingUtilities {

    / **
     *实用功能的图像资源进行解码。去codeD位将
     *进一步缩放进行优化,以所请求的目的地的尺寸
     *和缩放逻辑。
     *
     * @参数水库的资源对象包含图像数据
     * @参数残油的图象数据的资源ID
     目标区域的*参数dstWidth宽
     *参数dstHeight身高目标区域
     * @参数scalingLogic逻辑使用,以避免图像拉伸
     * @返回德codeD位图
     * /
    公共静态位图德codeResource(资源资源,字符串路径,INT dstWidth,INT dstHeight,
            ScalingLogic scalingLogic){
        选项​​选项=新的选项();
        options.inJustDe codeBounds = TRUE;
        //BitmapFactory.de$c$cResource(res,渣油,期权);
        options.inJustDe codeBounds = FALSE;
        options.inSampleSize = calculateSampleSize(options.outWidth,options.outHeight,dstWidth,
                dstHeight,scalingLogic);
        位图unscaledBitmap = BitmapFactory.de codeFILE(路径选择);

        返回unscaledBitmap;
    }

    / **
     *效用函数,用于创建现有的位图的缩放版本
     *
     * @参数unscaledBitmap位图缩放
     目标位图的*参数dstWidth通缉宽度
     目标位图的*参数dstHeight通缉高度
     * @参数scalingLogic逻辑使用,以避免图像拉伸
     * @返回新缩放位图对象
     * /
    公共静态位图createScaledBitmap(位图unscaledBitmap,诠释dstWidth,INT dstHeight,
            ScalingLogic scalingLogic){
        矩形srcRect = calculateSrcRect(unscaledBitmap.getWidth(),unscaledBitmap.getHeight(),
                dstWidth,dstHeight,scalingLogic);
        矩形dstRect = calculateDstRect(unscaledBitmap.getWidth(),unscaledBitmap.getHeight(),
                dstWidth,dstHeight,scalingLogic);
        位图scaledBitmap = Bitmap.createBitmap(dstRect.width(),dstRect.height(),
                Config.ARGB_8888);
        帆布油画=新的Canvas(scaledBitmap);
        canvas.drawBitmap(unscaledBitmap,srcRect,dstRect,新的油漆(Paint.FILTER_BITMAP_FLAG));

        返回scaledBitmap;
    }

    / **
     * ScalingLogic定义了如何定标应进行,如果源和
     *目的地形象有不同的纵横比。
     *
     *作物:缩放图像的最小量,同时确保至少有
     *两个维度符合要求的目标区域内的一个。
     *源图像的部分将被裁剪来实现这一点。
     *
     * FIT:缩放图像的最小量,同时确保这两个
     *尺寸符合要求的目标区域内。由此产生的
     *目的地尺寸可以被调整到一个较小的尺寸比
     *要求。
     * /
    公共静态枚举ScalingLogic {
        作物,FIT
    }

    / **
     *计算最佳向下采样因子给定源的尺寸
     *图像,目标区域的尺寸和缩放逻辑。
     *
     来源形象* @参数srcWidth宽
     * @参数srcHeight的源图像高度
     目标区域的*参数dstWidth宽
     *参数dstHeight身高目标区域
     * @参数scalingLogic逻辑使用,以避免图像拉伸
     * @返回最佳下来缩放的样本量进行解码
     * /
    公共静态INT calculateSampleSize(INT srcWidth,诠释srcHeight,诠释dstWidth,INT dstHeight,
            ScalingLogic scalingLogic){
        如果(scalingLogic == ScalingLogic.FIT){
            最终浮srcAspect =(浮点)srcWidth /(浮点)srcHeight;
            最终浮dstAspect =(浮点)dstWidth /(浮点)dstHeight;

            如果(srcAspect&GT; dstAspect){
                返回srcWidth / dstWidth;
            } 其他 {
                返回srcHeight / dstHeight;
            }
        } 其他 {
            最终浮srcAspect =(浮点)srcWidth /(浮点)srcHeight;
            最终浮dstAspect =(浮点)dstWidth /(浮点)dstHeight;

            如果(srcAspect&GT; dstAspect){
                返回srcHeight / dstHeight;
            } 其他 {
                返回srcWidth / dstWidth;
            }
        }
    }

    / **
     *计算源矩形缩放位图
     *
     来源形象* @参数srcWidth宽
     * @参数srcHeight的源图像高度
     目标区域的*参数dstWidth宽
     *参数dstHeight身高目标区域
     * @参数scalingLogic逻辑使用,以避免图像拉伸
     * @返回最优源矩形
     * /
    公共静态矩形calculateSrcRect(INT srcWidth,诠释srcHeight,诠释dstWidth,INT dstHeight,
            ScalingLogic scalingLogic){
        如果(scalingLogic == ScalingLogic.CROP){
            最终浮srcAspect =(浮点)srcWidth /(浮点)srcHeight;
            最终浮dstAspect =(浮点)dstWidth /(浮点)dstHeight;

            如果(srcAspect&GT; dstAspect){
                最终诠释srcRectWidth =(INT)(srcHeight * dstAspect);
                最终诠释srcRectLeft =(srcWidth  -  srcRectWidth)/ 2;
                返回新的矩形(srcRectLeft,0,srcRectLeft + srcRectWidth,srcHeight);
            } 其他 {
                最终诠释srcRectHeight =(INT)(srcWidth / dstAspect);
                最终诠释scrRectTop =(int)的(srcHeight  -  srcRectHeight)/ 2;
                返回新的矩形(0,scrRectTop,srcWidth,scrRectTop + srcRectHeight);
            }
        } 其他 {
            返回新的矩形(0,0,srcWidth,srcHeight);
        }
    }

    / **
     *计算目标矩形缩放位图
     *
     来源形象* @参数srcWidth宽
     * @参数srcHeight的源图像高度
     目标区域的*参数dstWidth宽
     *参数dstHeight身高目标区域
     * @参数scalingLogic逻辑使用,以避免图像拉伸
     * @返回最优目标矩形
     * /
    公共静态矩形calculateDstRect(INT srcWidth,诠释srcHeight,诠释dstWidth,INT dstHeight,
            ScalingLogic scalingLogic){
//如果(scalingLogic == ScalingLogic.FIT){
//最终浮srcAspect =(浮点)srcWidth /(浮点)srcHeight;
//最终浮dstAspect =(浮点)dstWidth /(浮点)dstHeight;
//
//如果(srcAspect&GT; dstAspect){
//返回新的矩形(0,0,dstWidth,(INT)(dstWidth / srcAspect));
//            } 其他 {
//返回新的矩形(0,0,(INT)(dstHeight * srcAspect),dstHeight);
//}
//        } 其他
        {
            返回新的矩形(0,0,dstWidth,dstHeight);
        }
    }


    公共静态位图performResize(位图unscaledBitmap,诠释的高度,诠释宽度)
    {
 //Log.e("Scaling位图,unscaledBitmap.toString()+高度+高度+W =+宽);
        位图scaledBitmap = ScalingUtilities.createScaledBitmap(unscaledBitmap,宽度,高度,ScalingUtilities.ScalingLogic.FIT);
//如果(scaledBitmap!= NULL)
// scaledBitmap = ImageBlurUtility.fastblur(LiveWallpaperService.bitmap,LiveWallpaperService.imageBlurAmount);
//

        unscaledBitmap.recycle();

        返回scaledBitmap;
    }

   公共静态位图updateImageFromGallary(上下文CTX,串imgPath,INT reqWidth,INT reqHeight)
    {
        位图cameraBitmap = NULL;
        尝试
        {
            cameraBitmap =去codeSampledBitmapFromResource(ctx.getResources(),imgPath,reqWidth,reqHeight);
            //imgEdit.setImageBitmap(cameraBitmap);
        }
        赶上(OutOfMemoryError异常outMemeoryError)
        {
           // Toast.makeText(这一点,无法加载图片,Toast.LENGTH_SHORT).show();
        }
        返回cameraBitmap;
    }

    公共静态位图德codeSampledBitmapFromResource(资源资源,字符串路径,INT reqWidth,INT reqHeight)
    {
        最后BitmapFactory.Options选项=新BitmapFactory.Options();
        options.inJustDe codeBounds = TRUE;
      options.inPurgeable = TRUE;
        BitmapFactory.de codeFILE(路径选择);

        //计算inSampleSize
        //options.inSampleSize = calculateInSampleSize(选项,reqWidth,reqHeight);


        options.inSampleSize = calculateInSampleSize(选项,reqWidth,reqHeight);

        与inSampleSize集//德code位图
        options.inJustDe codeBounds = FALSE;
       //返回BitmapFactory.de codeResource(RES,渣油,期权);

       //返回BitmapFactory.de codeFILE(路径选择);

          返回BitmapFactory.de codeFILE(路径选择);
    }

    公共静态INT calculateInSampleSize(BitmapFactory.Options选项,诠释reqWidth,INT reqHeight)
    {
    //原始高度和宽度的图像
    最终诠释身高= options.outHeight;
    最终诠释宽度= options.outWidth;
    INT inSampleSize = 1;

    如果(高度&GT; reqHeight ||宽度GT; reqWidth)
    {
        //计算的高度和宽度的比率要求的高度和宽度
        最终诠释heightRatio = Math.round((浮动)的高度/(浮点)reqHeight);
        最终诠释widthRatio = Math.round((浮点)宽/(浮点)reqWidth);

        //选择最小比例为inSampleSize值,这将保证
        //与两个尺寸大于或等于所述最终图像
        //请求的高度和宽度。
        inSampleSize = heightRatio&LT; widthRatio? heightRatio:widthRatio;
    }

    返回inSampleSize;
    }



/ **
 *此方法DP单元转换为等效的像素,这取决于器件密度。
 *
 *参数DP上的DP中(密度无关的像素)的单位价值。这就需要我们转换为像素
 * @参数上下文的背景下获得的资源和特定设备的显示指标
 返回:一个浮点值,重新present PX等值积分,取决于设备密度DP
 * /
公共静态浮动convertDpToPixel(浮DP,上下文语境){
    资源资源= context.getResources();
    DisplayMetrics度量= resources.getDisplayMetrics();
    浮动PX = DP *(metrics.densityDpi / 160F);
    返回像素;
}

/ **
 *此方法转换设备特定的像素密度独立的像素。
 *
 *参数PX的像素(像素)单元的值。这就需要我们转换成数据库
 * @参数上下文的背景下获得的资源和特定设备的显示指标
 返回:一个浮点值,重新present DP相当于像素值
 * /
公共静态浮动convertPixelsToDp(浮点像素,上下文的背景下){
    资源资源= context.getResources();
    DisplayMetrics度量= resources.getDisplayMetrics();
    浮DP = PX /(metrics.densityDpi / 160F);
    返回DP;
}


公共静态INT convertToPx(INT输入,上下文语境){
    //获取屏幕的密度天平
    最终浮动规模= context.getResources()getDisplayMetrics()密度。
    //将DPS像素,基于密度规模
    Log.e(TEXTSIZE,TEXTSIZE刻度值+规模);
    返程(INT)(输入*规模+ 0.5F);
}

}
 

I'm scaling down some bitmaps and getting low quality results. I tried the Bitmap#createScaledBitmap and the Canvas#drawBitmap method. Setting the filter parameter in the first and the filter flag in the Paint object of the second have shown no visible difference.

I tried solutions founded in these questions:

Bad image quality after resizing/scaling bitmap

Quality problems when resizing an image at runtime

Drawing scaled bitmaps on a SurfaceView -- no antialiasing

And some others.

As someone said somewhere, the filter flag in createScaledBitmap or in a Paint object enables the bicubic interpolation algorithm. However, it makes no difference. Using GIMP cubic, which is in fact bicubic, the resulting image is much better than the Android implementation.

API level here is 19.

解决方案

Try this one..

private Bitmap performResize(Bitmap bitmap, int requiredWidth,
            int requiredHeight) {
        int imageWidth = bitmap.getWidth();
        int imageHeight = bitmap.getHeight();
        float differenceWidth = requiredWidth - imageWidth;
        float percentage = differenceWidth / imageWidth * 100;
        float estimatedheight = imageHeight + (percentage * imageHeight / 100);
        float estimatedwidth = requiredWidth;

        if (estimatedheight < requiredHeight) {
            float incresePercentage = (float) (requiredHeight - estimatedheight);
            percentage += (incresePercentage / imageHeight * 100);
            estimatedheight = imageHeight + (percentage * imageHeight / 100);
            estimatedwidth = imageWidth + (percentage * imageWidth / 100);
        }

        bitmap = ScalingUtilities.performResize(bitmap, (int) estimatedheight,
                (int) estimatedwidth);

        if (bitmap.getHeight() < requiredHeight) // if calculate height is
                                                    // smaller then the required
                                                    // Height
        {
        } else {
            int xCropPosition = (int) ((bitmap.getWidth() - requiredWidth) / 2);
            int yCropPosition = (int) ((bitmap.getHeight() - requiredHeight) / 2);

            bitmap = Bitmap.createBitmap(bitmap, xCropPosition, yCropPosition,
                    (int) requiredWidth, (int) requiredHeight);
        }
        return bitmap;
    }

utility file

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.DisplayMetrics;
import android.util.Log;

/**
 * Class containing static utility methods for bitmap decoding and scaling
 *
 * @author Andreas Agvard (andreas.agvard@sonyericsson.com)
 */
public class ScalingUtilities {

    /**
     * Utility function for decoding an image resource. The decoded bitmap will
     * be optimized for further scaling to the requested destination dimensions
     * and scaling logic.
     *
     * @param res The resources object containing the image data
     * @param resId The resource id of the image data
     * @param dstWidth Width of destination area
     * @param dstHeight Height of destination area
     * @param scalingLogic Logic to use to avoid image stretching
     * @return Decoded bitmap
     */
    public static Bitmap decodeResource(Resources res, String path, int dstWidth, int dstHeight,
            ScalingLogic scalingLogic) {
        Options options = new Options();
        options.inJustDecodeBounds = true;
        //BitmapFactory.decodeResource(res, resId, options);
        options.inJustDecodeBounds = false;
        options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, dstWidth,
                dstHeight, scalingLogic);
        Bitmap unscaledBitmap = BitmapFactory.decodeFile(path, options);

        return unscaledBitmap;
    }

    /**
     * Utility function for creating a scaled version of an existing bitmap
     *
     * @param unscaledBitmap Bitmap to scale
     * @param dstWidth Wanted width of destination bitmap
     * @param dstHeight Wanted height of destination bitmap
     * @param scalingLogic Logic to use to avoid image stretching
     * @return New scaled bitmap object
     */
    public static Bitmap createScaledBitmap(Bitmap unscaledBitmap, int dstWidth, int dstHeight,
            ScalingLogic scalingLogic) {
        Rect srcRect = calculateSrcRect(unscaledBitmap.getWidth(), unscaledBitmap.getHeight(),
                dstWidth, dstHeight, scalingLogic);
        Rect dstRect = calculateDstRect(unscaledBitmap.getWidth(), unscaledBitmap.getHeight(),
                dstWidth, dstHeight, scalingLogic);
        Bitmap scaledBitmap = Bitmap.createBitmap(dstRect.width(), dstRect.height(),
                Config.ARGB_8888);
        Canvas canvas = new Canvas(scaledBitmap);
        canvas.drawBitmap(unscaledBitmap, srcRect, dstRect, new Paint(Paint.FILTER_BITMAP_FLAG));

        return scaledBitmap;
    }

    /**
     * ScalingLogic defines how scaling should be carried out if source and
     * destination image has different aspect ratio.
     *
     * CROP: Scales the image the minimum amount while making sure that at least
     * one of the two dimensions fit inside the requested destination area.
     * Parts of the source image will be cropped to realize this.
     *
     * FIT: Scales the image the minimum amount while making sure both
     * dimensions fit inside the requested destination area. The resulting
     * destination dimensions might be adjusted to a smaller size than
     * requested.
     */
    public static enum ScalingLogic {
        CROP, FIT
    }

    /**
     * Calculate optimal down-sampling factor given the dimensions of a source
     * image, the dimensions of a destination area and a scaling logic.
     *
     * @param srcWidth Width of source image
     * @param srcHeight Height of source image
     * @param dstWidth Width of destination area
     * @param dstHeight Height of destination area
     * @param scalingLogic Logic to use to avoid image stretching
     * @return Optimal down scaling sample size for decoding
     */
    public static int calculateSampleSize(int srcWidth, int srcHeight, int dstWidth, int dstHeight,
            ScalingLogic scalingLogic) {
        if (scalingLogic == ScalingLogic.FIT) {
            final float srcAspect = (float)srcWidth / (float)srcHeight;
            final float dstAspect = (float)dstWidth / (float)dstHeight;

            if (srcAspect > dstAspect) {
                return srcWidth / dstWidth;
            } else {
                return srcHeight / dstHeight;
            }
        } else {
            final float srcAspect = (float)srcWidth / (float)srcHeight;
            final float dstAspect = (float)dstWidth / (float)dstHeight;

            if (srcAspect > dstAspect) {
                return srcHeight / dstHeight;
            } else {
                return srcWidth / dstWidth;
            }
        }
    }

    /**
     * Calculates source rectangle for scaling bitmap
     *
     * @param srcWidth Width of source image
     * @param srcHeight Height of source image
     * @param dstWidth Width of destination area
     * @param dstHeight Height of destination area
     * @param scalingLogic Logic to use to avoid image stretching
     * @return Optimal source rectangle
     */
    public static Rect calculateSrcRect(int srcWidth, int srcHeight, int dstWidth, int dstHeight,
            ScalingLogic scalingLogic) {
        if (scalingLogic == ScalingLogic.CROP) {
            final float srcAspect = (float)srcWidth / (float)srcHeight;
            final float dstAspect = (float)dstWidth / (float)dstHeight;

            if (srcAspect > dstAspect) {
                final int srcRectWidth = (int)(srcHeight * dstAspect);
                final int srcRectLeft = (srcWidth - srcRectWidth) / 2;
                return new Rect(srcRectLeft, 0, srcRectLeft + srcRectWidth, srcHeight);
            } else {
                final int srcRectHeight = (int)(srcWidth / dstAspect);
                final int scrRectTop = (int)(srcHeight - srcRectHeight) / 2;
                return new Rect(0, scrRectTop, srcWidth, scrRectTop + srcRectHeight);
            }
        } else {
            return new Rect(0, 0, srcWidth, srcHeight);
        }
    }

    /**
     * Calculates destination rectangle for scaling bitmap
     *
     * @param srcWidth Width of source image
     * @param srcHeight Height of source image
     * @param dstWidth Width of destination area
     * @param dstHeight Height of destination area
     * @param scalingLogic Logic to use to avoid image stretching
     * @return Optimal destination rectangle
     */
    public static Rect calculateDstRect(int srcWidth, int srcHeight, int dstWidth, int dstHeight,
            ScalingLogic scalingLogic) {
//        if (scalingLogic == ScalingLogic.FIT) {
//            final float srcAspect = (float)srcWidth / (float)srcHeight;
//            final float dstAspect = (float)dstWidth / (float)dstHeight;
//
//            if (srcAspect > dstAspect) {
//                return new Rect(0, 0, dstWidth, (int)(dstWidth / srcAspect));
//            } else {
//                return new Rect(0, 0, (int)(dstHeight * srcAspect), dstHeight);
//            }
//        } else 
        {
            return new Rect(0, 0, dstWidth, dstHeight);
        }
    }


    public static Bitmap performResize(Bitmap unscaledBitmap,int height,int width)
    {
 //Log.e("Scaling Bitmap",unscaledBitmap.toString() + " height" +height +" w="+width );
        Bitmap scaledBitmap = ScalingUtilities.createScaledBitmap(unscaledBitmap,  width, height, ScalingUtilities.ScalingLogic.FIT);
//        if(scaledBitmap != null )
//          scaledBitmap = ImageBlurUtility.fastblur(LiveWallpaperService.bitmap, LiveWallpaperService.imageBlurAmount);
//          

        unscaledBitmap.recycle();

        return scaledBitmap;
    }

   public static Bitmap updateImageFromGallary(Context ctx,String imgPath,int reqWidth, int reqHeight)
    {
        Bitmap cameraBitmap=null; 
        try
        {     
            cameraBitmap = decodeSampledBitmapFromResource(ctx.getResources(),imgPath,reqWidth,reqHeight);
            //imgEdit.setImageBitmap(cameraBitmap); 
        }
        catch(OutOfMemoryError outMemeoryError)
        {
           // Toast.makeText(this, "Unable to Load Image", Toast.LENGTH_SHORT).show(); 
        }  
        return cameraBitmap;
    }

    public static Bitmap decodeSampledBitmapFromResource(Resources res, String path,int reqWidth, int reqHeight) 
    {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
      options.inPurgeable = true;
        BitmapFactory.decodeFile(path, options);

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


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

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

       // return  BitmapFactory.decodeFile(path, options);

          return  BitmapFactory.decodeFile(path, 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 = 1;

    if (height > reqHeight || width > reqWidth) 
    {
        // Calculate ratios of height and width to requested height and width
        final int heightRatio = Math.round((float) height / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);

        // Choose the smallest ratio as inSampleSize value, this will guarantee
        // a final image with both dimensions larger than or equal to the
        // requested height and width.
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
    }

    return inSampleSize;
    }



/**
 * This method converts dp unit to equivalent pixels, depending on device density. 
 * 
 * @param dp A value in dp (density independent pixels) unit. Which we need to convert into pixels
 * @param context Context to get resources and device specific display metrics
 * @return A float value to represent px equivalent to dp depending on device density
 */
public static float convertDpToPixel(float dp, Context context){
    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    float px = dp * (metrics.densityDpi / 160f);
    return px;
}

/**
 * This method converts device specific pixels to density independent pixels.
 * 
 * @param px A value in px (pixels) unit. Which we need to convert into db
 * @param context Context to get resources and device specific display metrics
 * @return A float value to represent dp equivalent to px value
 */
public static float convertPixelsToDp(float px, Context context) {
    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    float dp = px / (metrics.densityDpi / 160f);
    return dp;
}


public static int convertToPx(int input,Context context) {
    // Get the screen's density scale
    final float scale = context.getResources().getDisplayMetrics().density;
    // Convert the dps to pixels, based on density scale
    Log.e("textSize","textSize scale value "+scale);
    return (int) (input * scale + 0.5f);
}

}

这篇关于安卓:位图向下扩展低质量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆