android压缩图片的算法

  1. /** 
  2.      * 压缩图片 
  3.      * @param bitmap 源图片 
  4.      * @param width 想要的宽度 
  5.      * @param height 想要的高度 
  6.      * @param isAdjust 是否自动调整尺寸, true图片就不会拉伸,false严格按照你的尺寸压缩 
  7.      * @return Bitmap 
  8.      */  
  9.     public Bitmap reduce(Bitmap bitmap, int width, int height, boolean isAdjust) {  
  10.         // 如果想要的宽度和高度都比源图片小,就不压缩了,直接返回原图  
  11.         if (bitmap.getWidth() < width && bitmap.getHeight() < height) {return bitmap;}  
  12.         // 根据想要的尺寸精确计算压缩比例, 方法详解:public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode);  
  13.         // scale表示要保留的小数位, roundingMode表示如何处理多余的小数位,BigDecimal.ROUND_DOWN表示自动舍弃  
  14.         float sx = new BigDecimal(width).divide(new BigDecimal(bitmap.getWidth()), 4, BigDecimal.ROUND_DOWN).floatValue();  
  15.         float sy = new BigDecimal(height).divide(new BigDecimal(bitmap.getHeight()), 4, BigDecimal.ROUND_DOWN).floatValue();  
  16.         if (isAdjust) {// 如果想自动调整比例,不至于图片会拉伸  
  17.             sx = (sx < sy ? sx : sy);sy = sx;// 哪个比例小一点,就用哪个比例  
  18.         }  
  19.         Matrix matrix = new Matrix();  
  20.         matrix.postScale(sx, sy);// 调用api中的方法进行压缩,就大功告成了  
  21.         return Bitmap.createBitmap(bitmap, 00, bitmap.getWidth(), bitmap.getHeight(), matrix, true);  
  22.     }  

旋转图片:

[java]  view plain copy
  1. /** 
  2.      * 旋转图片 
  3.      * @param bitmap 源图片 
  4.      * @param angle 旋转角度(90为顺时针旋转,-90为逆时针旋转) 
  5.      * @return Bitmap 
  6.      */  
  7.     public Bitmap rotate(Bitmap bitmap, float angle) {  
  8.         Matrix matrix = new Matrix();    
  9.         matrix.postRotate(angle);  
  10.         return Bitmap.createBitmap(bitmap, 00, bitmap.getWidth(), bitmap.getHeight(), matrix, true);  
  11.     }  
放大或缩小图片:
[java]  view plain copy
  1. /** 
  2.      * 放大或缩小图片 
  3.      * @param bitmap 源图片 
  4.      * @param ratio 放大或缩小的倍数,大于1表示放大,小于1表示缩小 
  5.      * @return Bitmap 
  6.      */  
  7.     public Bitmap zoom(Bitmap bitmap, float ratio) {  
  8.         if (ratio < 0f) {return bitmap;}  
  9.         Matrix matrix = new Matrix();  
  10.         matrix.postScale(ratio, ratio);  
  11.         return Bitmap.createBitmap(bitmap, 00, bitmap.getWidth(), bitmap.getHeight(), matrix, true);  
  12.     }  

在图片上印字:

[java]  view plain copy
  1. /** 
  2.      * 在图片上印字 
  3.      * @param bitmap 源图片 
  4.      * @param text 印上去的字 
  5.      * @param param 字体参数分别为:颜色,大小,是否加粗,起点x,起点y; 比如:{color : 0xFF000000, size : 30, bold : true, x : 20, y : 20} 
  6.      * @return Bitmap 
  7.      */  
  8.     public Bitmap printWord(Bitmap bitmap, String text, Map<String, Object> param) {  
  9.         if (ToolUtil.get().isBlank(text) || null == param) {return bitmap;}  
  10.         Bitmap newBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);  
  11.         Canvas canvas = new Canvas(newBitmap);  
  12.         canvas.drawBitmap(bitmap, 00null);canvas.save(Canvas.ALL_SAVE_FLAG);canvas.restore();  
  13.         Paint paint = new Paint();  
  14.         paint.setColor(null != param.get("color") ? (Integer) param.get("color") : Color.BLACK);  
  15.         paint.setTextSize(null != param.get("size") ? (Integer) param.get("size") : 20);  
  16.         paint.setFakeBoldText(null != param.get("bold") ? (Boolean) param.get("bold") : false);  
  17.         canvas.drawText(text, null != param.get("x") ? (Integer) param.get("x") : 0null != param.get("y") ? (Integer) param.get("y") : 0, paint);  
  18.         canvas.save(Canvas.ALL_SAVE_FLAG);canvas.restore();  
  19.         return newBitmap;  
  20.     }  

创建logo(给图片加水印), :
[java]  view plain copy
  1. /** 
  2.      * 创建logo(给图片加水印),  
  3.      * @param bitmaps 原图片和水印图片 
  4.      * @param left 左边起点坐标 
  5.      * @param top 顶部起点坐标t 
  6.      * @return Bitmap 
  7.      */  
  8.     public Bitmap createLogo(Bitmap[] bitmaps, int left, int top) {  
  9.         Bitmap newBitmap = Bitmap.createBitmap(bitmaps[0].getWidth(), bitmaps[0].getHeight(), Config.ARGB_8888);  
  10.         Canvas canvas = new Canvas(newBitmap);  
  11.         for (int i = 0; i < bitmaps.length; i++) {  
  12.             if (i == 0) {  
  13.                 canvas.drawBitmap(bitmaps[0], 00null);  
  14.             } else {  
  15.                 canvas.drawBitmap(bitmaps[i], left, top, null);  
  16.             }  
  17.             canvas.save(Canvas.ALL_SAVE_FLAG);canvas.restore();  
  18.         }  
  19.         return newBitmap;  
  20.     }  
产生一个4位随机数字的图片验证码:

[java]  view plain copy
  1. private int width = 140, height = 40, codeLen = 4;  
  2.     private String checkCode = "";  
  3.     private Random random = new Random();  
  4.       
  5.     /** 
  6.      * 产生一个4位随机数字的图片验证码 
  7.      * @return Bitmap 
  8.      */  
  9.     public Bitmap createCode() {  
  10.         checkCode = "";  
  11.         String[] chars = { "0""1""2""3""4""5""6""7""8""9" };  
  12.         for (int i = 0; i < codeLen; i++) {checkCode += chars[random.nextInt(chars.length)];}  
  13.         Bitmap bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);  
  14.         Canvas canvas = new Canvas(bitmap);canvas.drawColor(Color.WHITE);  
  15.         Paint paint = new Paint();paint.setTextSize(30);paint.setColor(Color.BLUE);  
  16.         for (int i = 0; i < checkCode.length(); i++) {  
  17.             paint.setColor(randomColor(1));paint.setFakeBoldText(random.nextBoolean());  
  18.             float skewX = random.nextInt(11) / 10;  
  19.             paint.setTextSkewX(random.nextBoolean() ? skewX : -skewX);  
  20.             int x = width / codeLen * i + random.nextInt(10);  
  21.             canvas.drawText(String.valueOf(checkCode.charAt(i)), x, 28, paint);  
  22.         }  
  23.         for (int i = 0; i < 3; i++) {drawLine(canvas, paint);}  
  24.         for (int i = 0; i < 255; i++) {drawPoints(canvas, paint);}  
  25.         canvas.save(Canvas.ALL_SAVE_FLAG);canvas.restore();  
  26.         return bitmap;  
  27.     }  
  28.       
  29.     /** 
  30.      * 获得一个随机的颜色 
  31.      * @param rate 
  32.      * @return  
  33.      */  
  34.     public int randomColor(int rate) {  
  35.         int red = random.nextInt(256) / rate, green = random.nextInt(256) / rate, blue = random.nextInt(256) / rate;  
  36.         return Color.rgb(red, green, blue);  
  37.     }  
  38.   
  39.     /** 
  40.      * 画随机线条 
  41.      * @param canvas 
  42.      * @param paint 
  43.      */  
  44.     public void drawLine(Canvas canvas, Paint paint) {  
  45.         int startX = random.nextInt(width), startY = random.nextInt(height);  
  46.         int stopX = random.nextInt(width), stopY = random.nextInt(height);  
  47.         paint.setStrokeWidth(1);paint.setColor(randomColor(1));  
  48.         canvas.drawLine(startX, startY, stopX, stopY, paint);  
  49.     }  
  50.   
  51.     /** 
  52.      * 画随机干扰点 
  53.      * @param canvas 
  54.      * @param paint 
  55.      */  
  56.     public void drawPoints(Canvas canvas, Paint paint) {  
  57.         int stopX = random.nextInt(width), stopY = random.nextInt(height);  
  58.         paint.setStrokeWidth(1);  
  59.         paint.setColor(randomColor(1));  
  60.         canvas.drawPoint(stopX, stopY, paint);  
  61.     }  
  62.       
  63.     /** 
  64.      * 返回真实验证码字符串 
  65.      * @return String 
  66.      */  
  67.     public String getCheckCode() {  
  68.         return checkCode;  
  69.     }  

Java代码   收藏代码
  1. private Bitmap compressImage(Bitmap image) {  
  2.   
  3.         ByteArrayOutputStream baos = new ByteArrayOutputStream();  
  4.         image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中  
  5.         int options = 100;  
  6.         while ( baos.toByteArray().length / 1024>100) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩         
  7.             baos.reset();//重置baos即清空baos  
  8.             image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中  
  9.             options -= 10;//每次都减少10  
  10.         }  
  11.         ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中  
  12.         Bitmap bitmap = BitmapFactory.decodeStream(isBm, nullnull);//把ByteArrayInputStream数据生成图片  
  13.         return bitmap;  
  14.     }  
 

第二:图片按比例大小压缩方法(根据路径获取图片并压缩):

 

 

Java代码   收藏代码
  1. private Bitmap getimage(String srcPath) {  
  2.         BitmapFactory.Options newOpts = new BitmapFactory.Options();  
  3.         //开始读入图片,此时把options.inJustDecodeBounds 设回true了  
  4.         newOpts.inJustDecodeBounds = true;  
  5.         Bitmap bitmap = BitmapFactory.decodeFile(srcPath,newOpts);//此时返回bm为空  
  6.           
  7.         newOpts.inJustDecodeBounds = false;  
  8.         int w = newOpts.outWidth;  
  9.         int h = newOpts.outHeight;  
  10.         //现在主流手机比较多是800*480分辨率,所以高和宽我们设置为  
  11.         float hh = 800f;//这里设置高度为800f  
  12.         float ww = 480f;//这里设置宽度为480f  
  13.         //缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可  
  14.         int be = 1;//be=1表示不缩放  
  15.         if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放  
  16.             be = (int) (newOpts.outWidth / ww);  
  17.         } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放  
  18.             be = (int) (newOpts.outHeight / hh);  
  19.         }  
  20.         if (be <= 0)  
  21.             be = 1;  
  22.         newOpts.inSampleSize = be;//设置缩放比例  
  23.         //重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了  
  24.         bitmap = BitmapFactory.decodeFile(srcPath, newOpts);  
  25.         return compressImage(bitmap);//压缩好比例大小后再进行质量压缩  
  26.     }  
 

第三:图片按比例大小压缩方法(根据Bitmap图片压缩):

 

Java代码   收藏代码
  1. private Bitmap comp(Bitmap image) {  
  2.       
  3.     ByteArrayOutputStream baos = new ByteArrayOutputStream();         
  4.     image.compress(Bitmap.CompressFormat.JPEG, 100, baos);  
  5.     if( baos.toByteArray().length / 1024>1024) {//判断如果图片大于1M,进行压缩避免在生成图片(BitmapFactory.decodeStream)时溢出    
  6.         baos.reset();//重置baos即清空baos  
  7.         image.compress(Bitmap.CompressFormat.JPEG, 50, baos);//这里压缩50%,把压缩后的数据存放到baos中  
  8.     }  
  9.     ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());  
  10.     BitmapFactory.Options newOpts = new BitmapFactory.Options();  
  11.     //开始读入图片,此时把options.inJustDecodeBounds 设回true了  
  12.     newOpts.inJustDecodeBounds = true;  
  13.     Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);  
  14.     newOpts.inJustDecodeBounds = false;  
  15.     int w = newOpts.outWidth;  
  16.     int h = newOpts.outHeight;  
  17.     //现在主流手机比较多是800*480分辨率,所以高和宽我们设置为  
  18.     float hh = 800f;//这里设置高度为800f  
  19.     float ww = 480f;//这里设置宽度为480f  
  20.     //缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可  
  21.     int be = 1;//be=1表示不缩放  
  22.     if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放  
  23.         be = (int) (newOpts.outWidth / ww);  
  24.     } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放  
  25.         be = (int) (newOpts.outHeight / hh);  
  26.     }  
  27.     if (be <= 0)  
  28.         be = 1;  
  29.     newOpts.inSampleSize = be;//设置缩放比例  
  30.     //重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了  
  31.     isBm = new ByteArrayInputStream(baos.toByteArray());  
  32.     bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);  
  33.     return compressImage(bitmap);//压缩好比例大小后再进行质量压缩  
  34. }  

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值