BitmapTool(封装工具类)

1.封装

  1 /**
  2  * 生成二维码
  3  */
  4 public class BitmapTool {
  5     public static Bitmap Create2DCode(String str, int color)
  6             throws WriterException {
  7         // 生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败
  8         BitMatrix matrix = new MultiFormatWriter().encode(str,
  9                 BarcodeFormat.QR_CODE, 500, 500);
 10         int width = matrix.getWidth();
 11         int height = matrix.getHeight();
 12         GoloLog.i("tag", "BitmapTool codebitmap height=="+width+"//"+height, null);
 13         // 二维矩阵转为一维像素数组,也就是一直横着排了
 14         int[] pixels = new int[width * height];
 15         for (int y = 0; y < height; y++) {
 16             for (int x = 0; x < width; x++) {
 17                 if (matrix.get(x, y)) {
 18                     pixels[y * width + x] = color;
 19                 } else {
 20                     pixels[y * width + x] = 0xffffffff;
 21                 }
 22             }
 23         }
 24         Bitmap bitmap = Bitmap.createBitmap(width, height,
 25                 Bitmap.Config.ARGB_8888);
 26         // 通过像素数组生成bitmap,具体参考api
 27         bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
 28         return bitmap;
 29     }
 30 
 31     public static Bitmap decodeCircleBitmap(String path)
 32     {
 33         Bitmap bitmap = null;
 34         try{
 35            bitmap = BitmapFactory.decodeFile(path);
 36         }catch(OutOfMemoryError E){
 37             E.printStackTrace();
 38         }
 39         if(bitmap!=null)
 40         {
 41 //            int width = bitmap.getWidth();
 42 //            int height = bitmap.getHeight();
 43 //            Bitmap faceBitmap = Bitmap.createBitmap(width,height, Bitmap.Config.ARGB_8888);
 44 //            Canvas canvas = new Canvas(faceBitmap);
 45 //            Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
 46 //            canvas.drawCircle(width/2f,height/2f,width*9/20f,paint);
 47 //            paint.setAntiAlias(true);
 48 //            paint.setFilterBitmap(true);
 49 //            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
 50 //            canvas.drawBitmap(bitmap,0,0,paint);
 51 //            bitmap.recycle();
 52             return bitmap;
 53         }
 54         return null;
 55     }
 56     public static Bitmap decodeBitmap(String path)
 57     {
 58         Bitmap bitmap = null;
 59         try{
 60             bitmap = BitmapFactory.decodeFile(path);
 61         }catch(OutOfMemoryError E){
 62             E.printStackTrace();
 63         }
 64         if(bitmap!=null)
 65         {
 66             return bitmap;
 67         }
 68         return null;
 69     }
 70     
 71     /**
 72      * 图片按指定的大小进行相应的压缩
 73      * @param path
 74      * @param maxKB
 75      * @return
 76      * 2014-04-25
 77      */
 78     private static BitmapFactory.Options options = new BitmapFactory.Options();
 79     public static Bitmap decodeBitmapBySize(String path,int maxKB){
 80         if(path==null)
 81             return null;
 82         File file = new File(path);
 83         if (file.exists()) {
 84             try {
 85                 long length = file.length()/1024;
 86                 Log.i("jh", "source data size -------------------------"+length);
 87                 Log.i("jh", "maxKb size--------------------------------"+maxKB);
 88                 if (length > maxKB) { // 如果大于指定kb就压缩
 89                     if(options.inSampleSize==0) {
 90                         options.inSampleSize = 2;
 91                     } else {
 92                         options.inSampleSize *= 2;
 93                     }
 94                     Log.i("jh", "inSampleSize-------------------------"+options.inSampleSize);
 95                     options.inJustDecodeBounds = false;
 96                     Bitmap bitmap = BitmapFactory.decodeFile(path, options);
 97                     Log.i("jh", "bitmap is return-------------------------");
 98                     ByteArrayOutputStream baos = new ByteArrayOutputStream();
 99                     bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
100                     Log.i("jh", "zip source data size ---------------------"+baos.toByteArray().length/1000);
101                     options.inSampleSize = 0;
102                     return bitmap;
103                 } else {
104                     return BitmapFactory.decodeFile(path);
105                 }
106             } catch (Exception e) {
107                 Log.i("jh", "e---------------------------------"+e);
108                 return decodeBitmapBySize(path, maxKB);
109             }
110         }
111         return null;
112     }
113     
114 public static Bitmap BitmapCreateAssignThumbBySize(String path,int maxKB){
115         GoloLog.i("tag", "BitmapCreateAssignThumbBySize111",null);
116         BitmapFactory.Options options = new BitmapFactory.Options();
117         options.inJustDecodeBounds = true;
118         Bitmap bmp = BitmapFactory.decodeFile(path, options);
119         int height = options.outHeight * 100 / options.outWidth;
120         options.outWidth = 100;
121         options.outHeight = height;
122         //bmp = decodeBitmapBySize(path,100);
123         try {
124             File file = new File(path);
125             long length = file.length()/1024;
126             
127             if (length > maxKB) { // 如果大于指定kb就压缩
128                 //先按图片的宽和高进行压缩
129                 BitmapFactory.Options options2 = new BitmapFactory.Options();
130                 options2.inJustDecodeBounds = true;
131                 options2.inSampleSize = (int) (length/maxKB);
132                 options2.inJustDecodeBounds = false;
133                 options2.outHeight = options.outHeight;
134                 options2.outWidth = options.outWidth;
135                 Bitmap bitmap = BitmapFactory.decodeFile(path, options2);
136 //                return bitmap;
137                 ByteArrayOutputStream baos = new ByteArrayOutputStream();
138                 bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
139                 if(baos.toByteArray().length/1024>maxKB) {
140                     int option = 100; 
141                     int bitmapLength = baos.toByteArray().length/1024;
142                     while (bitmapLength > maxKB) {  //循环判断如果压缩后图片是否大于?kb,大于继续压缩 
143                         GoloLog.i("tag", "BitmapCreateAssignThumbBySize while len="+bitmapLength+"//"+maxKB,null);
144                         options2.inSampleSize = options2.inSampleSize+1;//再判断缩小
145                         baos.reset();//重置baos即清空baos  
146 //                        option -= 5;//每次都减少5
147                         bitmap = BitmapFactory.decodeFile(path, options2);
148                         bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);//这里压缩options%,把压缩后的数据存放到baos中  
149                         bitmapLength = baos.toByteArray().length/1024;
150                        
151                     } 
152                     ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中  
153                     return BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片  
154                 } else {
155                     return bitmap;
156                 }
157             } else {
158                 return BitmapFactory.decodeFile(path);
159             }
160         } catch (Exception e) {
161             return null;
162         }
163     }
164     
165     public static Bitmap BitmapCreateAssignThumb(String path){
166         
167         BitmapFactory.Options options = new BitmapFactory.Options();
168         options.inJustDecodeBounds = true;
169         Bitmap bmp = BitmapFactory.decodeFile(path, options);
170         int height = options.outHeight * 100 / options.outWidth;
171         options.outWidth = 100;
172         options.outHeight = height;
173         //bmp = decodeBitmapBySize(path,100);
174         try {
175             File file = new File(path);
176             long length = file.length()/1024;
177             int flag = 15;
178 //            if(length >15&&length<200){
179 //                flag = 15;
180 //            }
181             if(length>200){
182                 flag = 200;
183             }
184             if (length > flag) { // 如果大于指定kb就压缩
185                 //先按图片的宽和高进行压缩
186                 BitmapFactory.Options options2 = new BitmapFactory.Options();
187                 options2.inJustDecodeBounds = true;
188                 options2.inSampleSize = (int) (length/flag);
189                 options2.inJustDecodeBounds = false;
190                 options2.outHeight = options.outHeight;
191                 options2.outWidth = options.outWidth;
192                 Bitmap bitmap = BitmapFactory.decodeFile(path, options2);
193                 ByteArrayOutputStream baos = new ByteArrayOutputStream();
194                 bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
195                 if(baos.toByteArray().length/1024>flag) {
196                     int option = 100;  
197                     while (baos.toByteArray().length/1024 > flag) {  //循环判断如果压缩后图片是否大于?kb,大于继续压缩 
198                         baos.reset();//重置baos即清空baos  
199                         option -= 5;//每次都减少5
200                         bitmap.compress(Bitmap.CompressFormat.JPEG, option, baos);//这里压缩options%,把压缩后的数据存放到baos中  
201                     } 
202                     ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中  
203                     return BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片  
204                 } else {
205                     return bitmap;
206                 }
207             } else {
208                 return BitmapFactory.decodeFile(path);
209             }
210         } catch (Exception e) {
211             return null;
212         }
213     }
214 
215     public static Bitmap createThumb(Bitmap bitmap,int maxLength){
216         int width = bitmap.getWidth();
217         int height = bitmap.getHeight();
218         int length = width>height?width:height;
219         float scale = (float)maxLength / length;
220         int w = (int) (width*scale);
221         int h = (int) (height*scale);
222         Bitmap thumb = Bitmap.createBitmap(w,h, Bitmap.Config.ARGB_8888);
223         Canvas canvas = new Canvas(thumb);
224         Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
225         paint.setAntiAlias(true);
226         paint.setFilterBitmap(true);
227         Matrix matrix = new Matrix();
228         matrix.setScale((float)w/width,(float)h/height);
229         canvas.drawBitmap(bitmap,matrix,paint);
230         return thumb;
231     }
232 
233     public static Bitmap cutThumb(Bitmap bitmap,int w,int h){
234         int width = bitmap.getWidth();
235         int height = bitmap.getHeight();
236         Bitmap thumb = Bitmap.createBitmap(w,h, Bitmap.Config.ARGB_8888);
237         Canvas canvas = new Canvas(thumb);
238         Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
239         paint.setAntiAlias(true);
240         paint.setFilterBitmap(true);
241         Matrix matrix = new Matrix();
242         matrix.postTranslate((w-width)/2,(h-height)/2);
243         canvas.drawBitmap(bitmap,matrix,paint);
244         return thumb;
245     }
246 
247     public static Bitmap extractVideoThumb(String path, int resId){
248         Bitmap thumb = ThumbnailUtils.createVideoThumbnail(path, MediaStore.Video.Thumbnails.MINI_KIND);
249         Bitmap logo = BitmapFactory.decodeResource(ApplicationConfig.resouce, resId);
250         int width = thumb.getWidth();
251         int height = thumb.getHeight();
252         int minLength = width<height?width:height;
253         int w = logo.getWidth();
254         int h = logo.getHeight();
255         int minL = w<h?w:h;
256         float scale = (float)minLength/2/minL;
257         Canvas canvas = new Canvas(thumb);
258         Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
259         paint.setAntiAlias(true);
260         paint.setFilterBitmap(true);
261         Matrix matrix = new Matrix();
262         matrix.setScale(scale,scale);
263         matrix.postTranslate((width-w*scale)/2,(height-h*scale)/2);
264         canvas.drawBitmap(logo,matrix,paint);
265         logo.recycle();
266         return thumb;
267     }
268 
269     public static void saveToFile(Bitmap bitmap,File file){
270         ByteArrayOutputStream out = new ByteArrayOutputStream();
271         FileOutputStream save = null;
272         try {
273             bitmap.compress(Bitmap.CompressFormat.JPEG,100,out);
274             byte[] data = out.toByteArray();
275             save = new FileOutputStream(file);
276             save.write(data,0,data.length);
277         } catch (IOException e) {
278             e.printStackTrace();
279         }finally {
280             try {
281                 out.close();
282             } catch (IOException e) {
283                 e.printStackTrace();
284             }
285             if(save!=null){
286                 try {
287                     save.close();
288                 } catch (IOException e) {
289                     e.printStackTrace();
290                 }
291             }
292         }
293     }
294 
295     public Bitmap decodeBitmapByLength(String path,int maxLength){
296         BitmapFactory.Options options = new BitmapFactory.Options();
297         options.inJustDecodeBounds = true;
298         Bitmap bitmap = BitmapFactory.decodeFile(path,options);
299         int width = options.outWidth;
300         int height = options.outHeight;
301         int max = width>height?width:height;
302         if(bitmap!=null){
303             int scale = Math.round((float)max/maxLength);
304             options.inJustDecodeBounds = false;
305             options.inSampleSize = scale>1?scale:1;
306             bitmap.recycle();
307             return BitmapFactory.decodeFile(path,options);
308         }
309         return null;
310     }
311 
312     public byte[] compressAsByteArray(Bitmap bitmap,int maxKB){
313         if(bitmap!=null){
314             ByteArrayOutputStream out = new ByteArrayOutputStream();
315             try {
316                 byte[] data;
317                 int quality = 100;
318                 do{
319                     bitmap.compress(Bitmap.CompressFormat.JPEG,quality,out);
320                     data = out.toByteArray();
321                     quality -= 20;
322                 }while (data.length>maxKB);
323                 return data;
324             } finally {
325                 try {
326                     out.close();
327                 } catch (IOException e) {
328                     e.printStackTrace();
329                 }
330                 bitmap.recycle();
331             }
332         }
333         return null;
334     }
335 
336     public Bitmap compressAsBitmap(Bitmap bitmap,int maxKB){
337         byte[] data = compressAsByteArray(bitmap,maxKB);
338         if(data!=null){
339             return BitmapFactory.decodeByteArray(data,0,data.length);
340         }
341         return null;
342     }
343 
344     public Bitmap cutBitmapCenter(String path, int width, int height){
345         Bitmap bitmap = decodeBitmapBySize(path,1024);
346         if(bitmap!=null){
347             int oldWidth = bitmap.getWidth();
348             int oldHeight = bitmap.getHeight();
349             Bitmap thumb = Bitmap.createBitmap(width,height, Bitmap.Config.ARGB_8888);
350             Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
351             paint.setFilterBitmap(true);
352             paint.setAntiAlias(true);
353             Matrix matrix = new Matrix();
354             matrix.postTranslate(width-oldWidth,height-oldHeight);
355             Canvas canvas = new Canvas(thumb);
356             canvas.drawBitmap(bitmap,matrix,paint);
357             bitmap.recycle();
358             return thumb;
359         }
360         return null;
361     }
362 
363     public void saveBitmap(File file,Bitmap bitmap){
364         FileOutputStream save = null;
365         ByteArrayOutputStream out = new ByteArrayOutputStream();
366         try {
367             bitmap.compress(Bitmap.CompressFormat.JPEG,100,out);
368             byte[] data = out.toByteArray();
369             save = new FileOutputStream(file);
370             save.write(data,0,data.length);
371         } catch (IOException e) {
372             e.printStackTrace();
373         }finally {
374             try {
375                 out.close();
376             } catch (IOException e) {
377                 e.printStackTrace();
378             }
379             if(save!=null){
380                 try {
381                     save.close();
382                 } catch (IOException e) {
383                     e.printStackTrace();
384                 }
385             }
386         }
387     }
388 
389     public static Bitmap decodeBitmap(String path,int maxWidth,int maxHeight){
390         BitmapFactory.Options options = new BitmapFactory.Options();
391         options.inJustDecodeBounds = true;
392         BitmapFactory.decodeFile(path,options);
393         int width = options.outWidth;
394         int height = options.outHeight;
395         int scale;
396         if(width>height){
397             scale = width/maxWidth;
398         }else {
399             scale = height/maxHeight;
400         }
401         scale = scale>1?scale:1;
402         options.inJustDecodeBounds = false;
403         options.inSampleSize = scale;
404         try{
405              return BitmapFactory.decodeFile(path,options);
406         }catch (OutOfMemoryError e) {
407             // TODO: handle exception
408             e.printStackTrace();
409             return null;
410         }
411        
412     }
413 
414     public static byte[] compressBitmap(Bitmap bitmap,int maxSize){
415         ByteArrayOutputStream out = new ByteArrayOutputStream();
416         byte[] image = null;
417         for(int i = 100;i>0;i-=5){
418             bitmap.compress(Bitmap.CompressFormat.JPEG,i,out);
419             image = out.toByteArray();
420             if(image.length/1024<maxSize){
421                 return image;
422             }
423         }
424 //        return image;
425         if(null != out){
426             try {
427                 out.close();
428                 out = null;
429             } catch (IOException e) {
430                 e.printStackTrace();
431             }
432         }
433         return image;
434     }
435     public static byte[] compressShareBitmap(Bitmap bitmap,int maxSize){
436         
437         byte[] image = null;
438         for(int i = 100;i>0;i-=15){
439             ByteArrayOutputStream out = new ByteArrayOutputStream();
440             bitmap.compress(Bitmap.CompressFormat.JPEG,i,out);
441             image = out.toByteArray();
442             if(null != out){
443                 try {
444                     out.close();
445                     out = null;
446                 } catch (IOException e) {
447                     e.printStackTrace();
448                 }
449             }
450             if(image.length/1024<maxSize){
451                 break;
452             }
453         }
454         return image;
455     }
456     
457     /**
458      * 压缩图片
459      * @param bitmap 原图
460      * @param width 要压缩的宽度
461      * @param height 要压缩的高度
462      * @return
463      */
464     public static Bitmap zipBitmap(Bitmap bitmap, Options options, int width, int height) {
465         if(bitmap!=null){
466             ///下面这种处理带来的图片失贞有点严重
467             return bitmap;
468         }
469         return null;
470     }
471     
472     /**
473      * 压缩图片
474      * @param file 文件
475      * @param width 要压缩的宽度
476      * @param height 要压缩的高度
477      * @return
478      */
479     public static Bitmap zipBitmap(File file, int width, int height) {
480         if(file==null) return null;
481         BitmapFactory.Options options = new BitmapFactory.Options();
482         options.inSampleSize = 2;
483         Bitmap bitmap = BitmapFactory.decodeFile(file.getPath(), options);
484         return bitmap;
485     }
486     
487     /**
488      * 压缩图片
489      * @param String 文件的路径
490      * @param width 要压缩的宽度
491      * @param height 要压缩的高度
492      * @return
493      */
494     public static Bitmap zipBitmap(String path, int width, int height) {
495         if(TextUtils.isEmpty(path)) return null;
496         BitmapFactory.Options options = new BitmapFactory.Options();
497         options.inSampleSize = 2;
498         Bitmap bitmap = BitmapFactory.decodeFile(path, options);
499         return bitmap;
500     }
501     
502     /**
503      * 压缩图片
504      * @param resId 资源文件的ID
505      * @param width 要压缩的宽度
506      * @param height 要压缩的高度
507      * @return
508      */
509     public static Bitmap zipBitmap(int resId, int width, int height) {
510         if(resId<1) return null;
511         BitmapFactory.Options options = new BitmapFactory.Options();
512         options.inSampleSize = 2;
513         Bitmap bitmap = BitmapFactory.decodeResource(ApplicationConfig.resouce, resId, options);
514         return bitmap;
515     }
516     
517     /**
518      * 压缩图片
519      * @param resId 资源文件的ID
520      * @param width 要压缩的宽度
521      * @param height 要压缩的高度
522      * @return
523      */
524     public static Bitmap zipBitmap(InputStream stream, int width, int height) {
525         if(stream==null) return null;
526         BitmapFactory.Options options = new BitmapFactory.Options();
527         options.inSampleSize = 2;
528         Bitmap bitmap = BitmapFactory.decodeStream(stream, null, options);
529         return bitmap;
530     }
531     
532     /**
533      * 转化图片(将资源图片转化为bitmap)
534      * @param resId 资源文件的ID
535      * @return
536      */
537     public Bitmap decodeResource(int ResId){
538         Bitmap bitmap = BitmapFactory.decodeResource(ApplicationConfig.resouce,ResId);
539         return bitmap;
540     }
541     
542     public static Bitmap scaleImg(Bitmap bm, int newWidth, int newHeight) {
543         // 图片源
544         // Bitmap bm = BitmapFactory.decodeStream(getResources()
545         // .openRawResource(id));
546         // 获得图片的宽高
547         int width = bm.getWidth();
548         int height = bm.getHeight();
549         // 设置想要的大小
550         int newWidth1 = newWidth;
551         int newHeight1 = newHeight;
552         // 计算缩放比例
553         float scaleWidth = ((float) newWidth1) / width;
554         float scaleHeight = ((float) newHeight1) / height;
555         // 取得想要缩放的matrix参数
556         Matrix matrix = new Matrix();
557         matrix.postScale(scaleWidth, scaleHeight);
558         // 得到新的图片
559         Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix,
560                 true);
561         return newbm;
562 
563     }
564     
565 }

2.使用

    imgViewQRcode.setImageDrawable(new BitmapDrawable(Create2DCode(Singlton.getInstance(UserInfoManager.class).getUserId(),    0xff000000)));
    myQRCodePath=FileTool.getInstance().saveMyBitmap(Singlton.getInstance(UserInfoManager.class).getUserId(), Create2DCode(Singlton.getInstance(UserInfoManager.class).getUserId(),0xff000000));

 

posted @ 2015-03-14 15:28  种花小哥  阅读(604)  评论(0)    收藏  举报