700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 图片的压缩 (指定尺寸及比例压缩)

图片的压缩 (指定尺寸及比例压缩)

时间:2022-09-04 03:15:00

相关推荐

图片的压缩 (指定尺寸及比例压缩)

1.压缩到指定尺寸

//使用Bitmap加Matrix来缩放public static Drawable resizeImage(Bitmap bitmap, int w, int h) { Bitmap BitmapOrg = bitmap; int width = BitmapOrg.getWidth(); int height = BitmapOrg.getHeight(); int newWidth = w; int newHeight = h; float scaleWidth = ((float) newWidth) / width; float scaleHeight = ((float) newHeight) / height; Matrix matrix = new Matrix(); matrix.postScale(scaleWidth, scaleHeight); // if you want to rotate the Bitmap // matrix.postRotate(45); Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width, height, matrix, true); return new BitmapDrawable(resizedBitmap); }

优缺点分析:

优点 : 能将图片压缩导致定尺寸

缺点:比较耗费内存 要先获取整个图片加载到内存中 初始输入的 Bitmap只能通过BitmapFactory.decodeFile(productPath);

原始图片较大,会费内存

2.按照比例压缩

//使用BitmapFactory.Options的inSampleSize参数来缩放public static Drawable resizeImage2(String path,int width,int height) {BitmapFactory.Options options = new BitmapFactory.Options();options.inJustDecodeBounds = true;//不加载bitmap到内存中BitmapFactory.decodeFile(path,options); int outWidth = options.outWidth;int outHeight = options.outHeight;options.inDither = false;options.inPreferredConfig = Bitmap.Config.ARGB_8888;options.inSampleSize = 1;if (outWidth != 0 && outHeight != 0 && width != 0 && height != 0) {int sampleSize=(outWidth/width+outHeight/height)/2;Log.d(tag, "sampleSize = " + sampleSize);options.inSampleSize = sampleSize;}options.inJustDecodeBounds = false;return new BitmapDrawable(BitmapFactory.decodeFile(path, options));}

优缺点分析:

优点 :比较身内存,开始不需要加载整个图片到内存中.只获取原始图片的宽高就可以了~

缺点:只能按照几分之几压缩

options.inSampleSize

采样率只能是int值,宽高只能压缩到原来的1/2;1/3等等~~

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。