Resize a bitmap

    xiaoxiao2021-03-25  128

    /** * Resample bitmap. * 这个方法有两个缺陷: * 1、我们先要从磁盘上先将图片加载到内存,然后才能对图片进行缩放,在移动设备上对内存的要求比较高,这在一定程度上降级了性能。 * 2、我们使用Bitmap.createBitmap这个方法进行缩放,使用的是Java层面的方法来缩放,我们知道Java层面对图片,视频等进行处理是有性能损失的。 * @param bitmap Bitmap. * @param scale Resample ratio. * @return Get resampled bitmap. */ public static Bitmap scaleBitmap(Bitmap bitmap, float scale) { Matrix matrix = new Matrix(); matrix.postScale(scale, scale); //长和宽放大缩小的比例 Bitmap resizeBmp = Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true); return resizeBmp; } /** * 下面给出优化方案,优化我们也是基于上面两点问题给出的。一次性从磁盘上读取并缩放,而且这个缩放实在Native层,能够显著提高效率,代码如下: * 这段代码是google给出的,我们无需对它进行修改,在上面这段代码中我们使用BitmapFactory.Options的inScaled,inDensity,inTargetDensity来变相对图片进行缩放, * 但是这有一个局限,就是只能对图片进行等比例的放大或者缩小,不能按任意大小进行缩放 * */ protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); try { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(getAssets().open("g_b090.jpg"), null, options); int targetDensity = getResources().getDisplayMetrics().densityDpi; DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); int x = dm.widthPixels; int y = dm.heightPixels; options.inSampleSize = calculateInSampleSize(options, x, y); double xSScale = ((double)options.outWidth) / ((double)x); double ySScale = ((double)options.outHeight) / ((double)y); double startScale = xSScale > ySScale ? xSScale : ySScale; options.inScaled = true; options.inDensity = (int) (targetDensity*startScale); options.inTargetDensity = targetDensity; options.inJustDecodeBounds = false; Bitmap bitmap = BitmapFactory.decodeStream(getAssets().open("g_b090.jpg"), null, options); } catch (IOException e) { e.printStackTrace(); } } public 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) { 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; }
    转载请注明原文地址: https://ju.6miu.com/read-7043.html

    最新回复(0)