-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBitmapUtils.java
executable file
·1514 lines (1353 loc) · 52.4 KB
/
BitmapUtils.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.youth.xframe.utils;
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.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.os.Build;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
import android.view.View;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Bitmap工具类主要包括获取Bitmap和对Bitmap的操作
*/
public class XBitmapUtils {
private XBitmapUtils() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
/**
* 图片压缩处理(使用Options的方法)
* <p/>
* <br>
* <b>说明</b>使用方法:
* 首先你要将Options的inJustDecodeBounds属性设置为true,BitmapFactory.decode一次图片 。
* 然后将Options连同期望的宽度和高度一起传递到到本方法中。
* 之后再使用本方法的返回值做参数调用BitmapFactory.decode创建图片。
* <p/>
* <br>
* <b>说明</b>BitmapFactory创建bitmap会尝试为已经构建的bitmap分配内存
* ,这时就会很容易导致OOM出现。为此每一种创建方法都提供了一个可选的Options参数
* ,将这个参数的inJustDecodeBounds属性设置为true就可以让解析方法禁止为bitmap分配内存
* ,返回值也不再是一个Bitmap对象, 而是null。虽然Bitmap是null了,但是Options的outWidth、
* outHeight和outMimeType属性都会被赋值。
*
* @param reqWidth 目标宽度,这里的宽高只是阀值,实际显示的图片将小于等于这个值
* @param reqHeight 目标高度,这里的宽高只是阀值,实际显示的图片将小于等于这个值
*/
public static BitmapFactory.Options calculateInSampleSize(
final BitmapFactory.Options options, final int reqWidth,
final int reqHeight) {
// 源图片的高度和宽度
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > 400 || width > 450) {
if (height > reqHeight || width > reqWidth) {
// 计算出实际宽高和目标宽高的比率
final int heightRatio = Math.round((float) height
/ (float) reqHeight);
final int widthRatio = Math.round((float) width
/ (float) reqWidth);
// 选择宽和高中最小的比率作为inSampleSize的值,这样可以保证最终图片的宽和高
// 一定都会大于等于目标的宽和高。
inSampleSize = heightRatio < widthRatio ? heightRatio
: widthRatio;
}
}
// 设置压缩比例
options.inSampleSize = inSampleSize;
options.inJustDecodeBounds = false;
return options;
}
/**
* 获取一个指定大小的bitmap
*
* @param res Resources
* @param resId 图片ID
* @param reqWidth 目标宽度
* @param reqHeight 目标高度
*/
public static Bitmap getBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// BitmapFactory.Options options = new BitmapFactory.Options();
// options.inJustDecodeBounds = true;
// BitmapFactory.decodeResource(res, resId, options);
// options = BitmapHelper.calculateInSampleSize(options, reqWidth,
// reqHeight);
// return BitmapFactory.decodeResource(res, resId, options);
// 通过JNI的形式读取本地图片达到节省内存的目的
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Config.RGB_565;
options.inPurgeable = true;
options.inInputShareable = true;
InputStream is = res.openRawResource(resId);
return getBitmapFromStream(is, null, reqWidth, reqHeight);
}
/**
* 获取一个指定大小的bitmap
*
* @param reqWidth 目标宽度
* @param reqHeight 目标高度
*/
public static Bitmap getBitmapFromFile(String pathName, int reqWidth,
int reqHeight) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(pathName, options);
options = calculateInSampleSize(options, reqWidth, reqHeight);
return BitmapFactory.decodeFile(pathName, options);
}
/**
* 获取一个指定大小的bitmap
*
* @param data Bitmap的byte数组
* @param offset image从byte数组创建的起始位置
* @param length the number of bytes, 从offset处开始的长度
* @param reqWidth 目标宽度
* @param reqHeight 目标高度
*/
public static Bitmap getBitmapFromByteArray(byte[] data, int offset,
int length, int reqWidth, int reqHeight) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(data, offset, length, options);
options = calculateInSampleSize(options, reqWidth, reqHeight);
return BitmapFactory.decodeByteArray(data, offset, length, options);
}
/**
* 把bitmap转化为bytes
* Bitmap → byte[]
* @param bitmap 源Bitmap
* @return Byte数组
*/
public static byte[] getBytesFromBitmap(Bitmap bitmap) {
if (bitmap == null) {
return null;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
/**
* Stream转换成Byte
*
* @param inputStream InputStream
* @return Byte数组
*/
public static byte[] getBytesFromStream(InputStream inputStream) {
ByteArrayOutputStream os = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int len;
try {
while ((len = inputStream.read(buffer)) >= 0) {
os.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
return os.toByteArray();
}
/**
* 获取一个指定大小的bitmap
* byte[] → Bitmap
* @param b Byte数组
* @return 需要的Bitmap
*/
public static Bitmap getBitmapFromBytes(byte[] b) {
if (b.length != 0) {
return BitmapFactory.decodeByteArray(b, 0, b.length);
} else {
return null;
}
}
/**
* 获取一个指定大小的bitmap
*
* @param is 从输入流中读取Bitmap
* @param outPadding If not null, return the padding rect for the bitmap if it
* exists, otherwise set padding to [-1,-1,-1,-1]. If no bitmap
* is returned (null) then padding is unchanged.
* @param reqWidth 目标宽度
* @param reqHeight 目标高度
*/
public static Bitmap getBitmapFromStream(InputStream is, Rect outPadding,
int reqWidth, int reqHeight) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, outPadding, options);
options = calculateInSampleSize(options, reqWidth, reqHeight);
return BitmapFactory.decodeStream(is, outPadding, options);
}
/**
* 从View获取Bitmap
*
* @param view View
* @return Bitmap
*/
public static Bitmap getBitmapFromView(View view) {
if (view == null) {
return null;
}
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),
Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.layout(view.getLeft(), view.getTop(), view.getRight(),
view.getBottom());
view.draw(canvas);
return bitmap;
}
/**
* 把一个View的对象转换成bitmap
*
* @param view View
* @return Bitmap
*/
public static Bitmap getBitmapFromView2(View view) {
if (view == null) {
return null;
}
view.clearFocus();
view.setPressed(false);
// 能画缓存就返回false
boolean willNotCache = view.willNotCacheDrawing();
view.setWillNotCacheDrawing(false);
int color = view.getDrawingCacheBackgroundColor();
view.setDrawingCacheBackgroundColor(0);
if (color != 0) {
view.destroyDrawingCache();
}
view.buildDrawingCache();
Bitmap cacheBitmap = view.getDrawingCache();
if (cacheBitmap == null) {
XPrintUtils.e( "failed getViewBitmap(" + view + ") -->"+
new RuntimeException());
return null;
}
Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
// Restore the view
view.destroyDrawingCache();
view.setWillNotCacheDrawing(willNotCache);
view.setDrawingCacheBackgroundColor(color);
return bitmap;
}
/**
* 将Drawable转化为Bitmap
*
* @param drawable Drawable
* @return Bitmap
*/
public static Bitmap getBitmapFromDrawable(Drawable drawable) {
if (drawable == null) {
return null;
}
// 取 drawable 的长宽
int w = drawable.getIntrinsicWidth();
int h = drawable.getIntrinsicHeight();
// 取 drawable 的颜色格式
Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565;
// 建立对应 bitmap
Bitmap bitmap = Bitmap.createBitmap(w, h, config);
// 建立对应 bitmap 的画布
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, w, h);
// 把 drawable 内容画到画布中
drawable.draw(canvas);
return bitmap;
}
/**
* 将 Bitmap转化为Drawable
*
* @param bm Bitmap
* @return Drawable
*/
@SuppressWarnings("deprecation")
public static Drawable getDrawableFromBitmap(Bitmap bm) {
if (bm == null) {
return null;
}
return new BitmapDrawable(bm);
}
/**
* 合并Bitmap
*
* @param bgd 背景Bitmap
* @param fg 前景Bitmap
* @return 合成后的Bitmap
*/
public static Bitmap combineImages(Bitmap bgd, Bitmap fg) {
Bitmap bmp;
int width = bgd.getWidth() > fg.getWidth() ? bgd.getWidth() : fg
.getWidth();
int height = bgd.getHeight() > fg.getHeight() ? bgd.getHeight() : fg
.getHeight();
bmp = Bitmap.createBitmap(width, height, Config.ARGB_8888);
Paint paint = new Paint();
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_ATOP));
Canvas canvas = new Canvas(bmp);
canvas.drawBitmap(bgd, 0, 0, null);
canvas.drawBitmap(fg, 0, 0, paint);
return bmp;
}
/**
* 合并
*
* @param bgd 后景Bitmap
* @param fg 前景Bitmap
* @return 合成后Bitmap
*/
public static Bitmap combineImagesToSameSize(Bitmap bgd, Bitmap fg) {
Bitmap bmp;
int width = bgd.getWidth() < fg.getWidth() ? bgd.getWidth() : fg
.getWidth();
int height = bgd.getHeight() < fg.getHeight() ? bgd.getHeight() : fg
.getHeight();
if (fg.getWidth() != width && fg.getHeight() != height) {
fg = zoom(fg, width, height);
}
if (bgd.getWidth() != width && bgd.getHeight() != height) {
bgd = zoom(bgd, width, height);
}
bmp = Bitmap.createBitmap(width, height, Config.ARGB_8888);
Paint paint = new Paint();
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_ATOP));
Canvas canvas = new Canvas(bmp);
canvas.drawBitmap(bgd, 0, 0, null);
canvas.drawBitmap(fg, 0, 0, paint);
return bmp;
}
/**
* 放大缩小图片
*
* @param bitmap 源Bitmap
* @param w 宽
* @param h 高
* @return 目标Bitmap
*/
public static Bitmap zoom(Bitmap bitmap, int w, int h) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Matrix matrix = new Matrix();
float scaleWidht = ((float) w / width);
float scaleHeight = ((float) h / height);
matrix.postScale(scaleWidht, scaleHeight);
Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height,
matrix, true);
return newbmp;
}
/**
* 获得圆角的Bitmap
*
* @param bitmap 源Bitmap
* @param roundPx 圆角大小
* @return 期望Bitmap
*/
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
/**
* 获得带倒影的Bitmap
*
* @param bitmap 源Bitmap
* @return 带倒影的Bitmap
*/
public static Bitmap createReflectionBitmap(Bitmap bitmap) {
final int reflectionGap = 4;
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Matrix matrix = new Matrix();
matrix.preScale(1, -1);
Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, height / 2,
width, height / 2, matrix, false);
Bitmap bitmapWithReflection = Bitmap.createBitmap(width,
(height + height / 2), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmapWithReflection);
canvas.drawBitmap(bitmap, 0, 0, null);
Paint deafalutPaint = new Paint();
canvas.drawRect(0, height, width, height + reflectionGap, deafalutPaint);
canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);
Paint paint = new Paint();
LinearGradient shader = new LinearGradient(0, bitmap.getHeight(), 0,
bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff,
0x00ffffff, TileMode.CLAMP);
paint.setShader(shader);
// Set the Transfer mode to be porter duff and destination in
paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
// Draw a rectangle using the paint with our linear gradient
canvas.drawRect(0, height, width, bitmapWithReflection.getHeight()
+ reflectionGap, paint);
return bitmapWithReflection;
}
/**
* 压缩图片大小
*
* @param image 源Bitmap
* @return 压缩后的Bitmap
*/
public static Bitmap compressImage(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
int options = 100;
while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
baos.reset();// 重置baos即清空baos
image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%,把压缩后的数据存放到baos中
options -= 10;// 每次都减少10
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
return bitmap;
}
/**
* 将彩色图转换为灰度图
*
* @param img 源Bitmap
* @return 返回转换好的位图
*/
public static Bitmap convertGreyImg(Bitmap img) {
int width = img.getWidth(); // 获取位图的宽
int height = img.getHeight(); // 获取位图的高
int[] pixels = new int[width * height]; // 通过位图的大小创建像素点数组
img.getPixels(pixels, 0, width, 0, 0, width, height);
int alpha = 0xFF << 24;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
int grey = pixels[width * i + j];
int red = ((grey & 0x00FF0000) >> 16);
int green = ((grey & 0x0000FF00) >> 8);
int blue = (grey & 0x000000FF);
grey = (int) ((float) red * 0.3 + (float) green * 0.59 + (float) blue * 0.11);
grey = alpha | (grey << 16) | (grey << 8) | grey;
pixels[width * i + j] = grey;
}
}
Bitmap result = Bitmap.createBitmap(width, height, Config.RGB_565);
result.setPixels(pixels, 0, width, 0, 0, width, height);
return result;
}
/**
* 获得圆形的Bitmap
*
* @param bitmap 传入Bitmap对象
* @return 圆形Bitmap
*/
public static Bitmap getRoundBitmap(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
float roundPx;
float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;
if (width <= height) {
roundPx = width / 2;
top = 0;
bottom = width;
left = 0;
right = width;
height = width;
dst_left = 0;
dst_top = 0;
dst_right = width;
dst_bottom = width;
} else {
roundPx = height / 2;
float clip = (width - height) / 2;
left = clip;
right = width - clip;
top = 0;
bottom = height;
width = height;
dst_left = 0;
dst_top = 0;
dst_right = height;
dst_bottom = height;
}
Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect src = new Rect((int) left, (int) top, (int) right,
(int) bottom);
final Rect dst = new Rect((int) dst_left, (int) dst_top,
(int) dst_right, (int) dst_bottom);
final RectF rectF = new RectF(dst);
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, src, dst, paint);
return output;
}
/**
* Returns a Bitmap representing the thumbnail of the specified Bitmap. The
* size of the thumbnail is defined by the dimension
* android.R.dimen.launcher_application_icon_size.
* <p/>
* This method is not thread-safe and should be invoked on the UI thread
* only.
*
* @param bitmap The bitmap to get a thumbnail of.
* @param context The application's context.
* @return A thumbnail for the specified bitmap or the bitmap itself if the
* thumbnail could not be created.
*/
public static Bitmap createThumbnailBitmap(Bitmap bitmap, Context context) {
int sIconWidth = -1;
int sIconHeight = -1;
final Resources resources = context.getResources();
sIconWidth = sIconHeight = (int) resources
.getDimension(android.R.dimen.app_icon_size);
final Paint sPaint = new Paint();
final Rect sBounds = new Rect();
final Rect sOldBounds = new Rect();
Canvas sCanvas = new Canvas();
int width = sIconWidth;
int height = sIconHeight;
sCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG,
Paint.FILTER_BITMAP_FLAG));
final int bitmapWidth = bitmap.getWidth();
final int bitmapHeight = bitmap.getHeight();
if (width > 0 && height > 0) {
if (width < bitmapWidth || height < bitmapHeight) {
final float ratio = (float) bitmapWidth / bitmapHeight;
if (bitmapWidth > bitmapHeight) {
height = (int) (width / ratio);
} else if (bitmapHeight > bitmapWidth) {
width = (int) (height * ratio);
}
final Config c = (width == sIconWidth && height == sIconHeight) ? bitmap
.getConfig() : Config.ARGB_8888;
final Bitmap thumb = Bitmap.createBitmap(sIconWidth,
sIconHeight, c);
final Canvas canvas = sCanvas;
final Paint paint = sPaint;
canvas.setBitmap(thumb);
paint.setDither(false);
paint.setFilterBitmap(true);
sBounds.set((sIconWidth - width) / 2,
(sIconHeight - height) / 2, width, height);
sOldBounds.set(0, 0, bitmapWidth, bitmapHeight);
canvas.drawBitmap(bitmap, sOldBounds, sBounds, paint);
return thumb;
} else if (bitmapWidth < width || bitmapHeight < height) {
final Config c = Config.ARGB_8888;
final Bitmap thumb = Bitmap.createBitmap(sIconWidth,
sIconHeight, c);
final Canvas canvas = sCanvas;
final Paint paint = sPaint;
canvas.setBitmap(thumb);
paint.setDither(false);
paint.setFilterBitmap(true);
canvas.drawBitmap(bitmap, (sIconWidth - bitmapWidth) / 2,
(sIconHeight - bitmapHeight) / 2, paint);
return thumb;
}
}
return bitmap;
}
/**
* 生成水印图片 水印在右下角
*
* @param src the bitmap object you want proecss
* @param watermark the water mark above the src
* @return return a bitmap object ,if paramter's length is 0,return null
*/
public static Bitmap createWatermarkBitmap(Bitmap src, Bitmap watermark) {
if (src == null) {
return null;
}
int w = src.getWidth();
int h = src.getHeight();
int ww = watermark.getWidth();
int wh = watermark.getHeight();
// create the new blank bitmap
Bitmap newb = Bitmap.createBitmap(w, h, Config.ARGB_8888);// 创建一个新的和SRC长度宽度一样的位图
Canvas cv = new Canvas(newb);
// draw src into
cv.drawBitmap(src, 0, 0, null);// 在 0,0坐标开始画入src
// draw watermark into
cv.drawBitmap(watermark, w - ww + 5, h - wh + 5, null);// 在src的右下角画入水印
// save all clip
cv.save(Canvas.ALL_SAVE_FLAG);// 保存
// store
cv.restore();// 存储
return newb;
}
/**
* 重新编码Bitmap
*
* @param src 需要重新编码的Bitmap
* @param format 编码后的格式(目前只支持png和jpeg这两种格式)
* @param quality 重新生成后的bitmap的质量
* @return 返回重新生成后的bitmap
*/
public static Bitmap codec(Bitmap src, Bitmap.CompressFormat format,
int quality) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
src.compress(format, quality, os);
byte[] array = os.toByteArray();
return BitmapFactory.decodeByteArray(array, 0, array.length);
}
/**
* 图片压缩处理(使用compress的方法)
* <p/>
* <br>
* <b>说明</b> 如果bitmap本身的大小小于maxSize,则不作处理
*
* @param bitmap 要压缩的图片
* @param maxSize 压缩后的大小,单位kb
*/
public static void compress(Bitmap bitmap, double maxSize) {
// 将bitmap放至数组中,意在获得bitmap的大小(与实际读取的原文件要大)
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// 格式、质量、输出流
bitmap.compress(Bitmap.CompressFormat.PNG, 70, baos);
byte[] b = baos.toByteArray();
// 将字节换成KB
double mid = b.length / 1024;
// 获取bitmap大小 是允许最大大小的多少倍
double i = mid / maxSize;
// 判断bitmap占用空间是否大于允许最大空间 如果大于则压缩 小于则不压缩
if (i > 1) {
// 缩放图片 此处用到平方根 将宽带和高度压缩掉对应的平方根倍
// (保持宽高不变,缩放后也达到了最大占用空间的大小)
bitmap = scale(bitmap, bitmap.getWidth() / Math.sqrt(i),
bitmap.getHeight() / Math.sqrt(i));
}
}
/**
* 图片的缩放方法
*
* @param src :源图片资源
* @param newWidth :缩放后宽度
* @param newHeight :缩放后高度
*/
public static Bitmap scale(Bitmap src, double newWidth, double newHeight) {
// 记录src的宽高
float width = src.getWidth();
float height = src.getHeight();
// 创建一个matrix容器
Matrix matrix = new Matrix();
// 计算缩放比例
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// 开始缩放
matrix.postScale(scaleWidth, scaleHeight);
// 创建缩放后的图片
return Bitmap.createBitmap(src, 0, 0, (int) width, (int) height,
matrix, true);
}
/**
* 图片的缩放方法
*
* @param src :源图片资源
* @param scaleMatrix :缩放规则
*/
public static Bitmap scale(Bitmap src, Matrix scaleMatrix) {
return Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(),
scaleMatrix, true);
}
/**
* 图片的缩放方法
*
* @param src :源图片资源
* @param scaleX :横向缩放比例
* @param scaleY :纵向缩放比例
*/
public static Bitmap scale(Bitmap src, float scaleX, float scaleY) {
Matrix matrix = new Matrix();
matrix.postScale(scaleX, scaleY);
return Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(),
matrix, true);
}
/**
* 图片的缩放方法
*
* @param src :源图片资源
* @param scale :缩放比例
*/
public static Bitmap scale(Bitmap src, float scale) {
return scale(src, scale, scale);
}
/**
* 旋转图片
*
* @param angle 旋转角度
* @param bitmap 要旋转的图片
* @return 旋转后的图片
*/
public static Bitmap rotate(Bitmap bitmap, int angle) {
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), matrix, true);
}
/**
* 水平翻转图片
*
* @param bitmap 原图
* @return 水平翻转后的图片
*/
public static Bitmap reverseByHorizontal(Bitmap bitmap) {
Matrix matrix = new Matrix();
matrix.preScale(-1, 1);
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), matrix, false);
}
/**
* 垂直翻转图片
*
* @param bitmap 原图
* @return 垂直翻转后的图片
*/
public static Bitmap reverseByVertical(Bitmap bitmap) {
Matrix matrix = new Matrix();
matrix.preScale(1, -1);
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), matrix, false);
}
/**
* 更改图片色系,变亮或变暗
*
* @param delta 图片的亮暗程度值,越小图片会越亮,取值范围(0,24)
* @return
*/
public static Bitmap adjustTone(Bitmap src, int delta) {
if (delta >= 24 || delta <= 0) {
return null;
}
// 设置高斯矩阵
int[] gauss = new int[]{1, 2, 1, 2, 4, 2, 1, 2, 1};
int width = src.getWidth();
int height = src.getHeight();
Bitmap bitmap = Bitmap.createBitmap(width, height,
Config.RGB_565);
int pixR = 0;
int pixG = 0;
int pixB = 0;
int pixColor = 0;
int newR = 0;
int newG = 0;
int newB = 0;
int idx = 0;
int[] pixels = new int[width * height];
src.getPixels(pixels, 0, width, 0, 0, width, height);
for (int i = 1, length = height - 1; i < length; i++) {
for (int k = 1, len = width - 1; k < len; k++) {
idx = 0;
for (int m = -1; m <= 1; m++) {
for (int n = -1; n <= 1; n++) {
pixColor = pixels[(i + m) * width + k + n];
pixR = Color.red(pixColor);
pixG = Color.green(pixColor);
pixB = Color.blue(pixColor);
newR += (pixR * gauss[idx]);
newG += (pixG * gauss[idx]);
newB += (pixB * gauss[idx]);
idx++;
}
}
newR /= delta;
newG /= delta;
newB /= delta;
newR = Math.min(255, Math.max(0, newR));
newG = Math.min(255, Math.max(0, newG));
newB = Math.min(255, Math.max(0, newB));
pixels[i * width + k] = Color.argb(255, newR, newG, newB);
newR = 0;
newG = 0;
newB = 0;
}
}
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
/**
* 将彩色图转换为黑白图
*
* @param bmp 位图
* @return 返回转换好的位图
*/
public static Bitmap convertToBlackWhite(Bitmap bmp) {
int width = bmp.getWidth();
int height = bmp.getHeight();
int[] pixels = new int[width * height];
bmp.getPixels(pixels, 0, width, 0, 0, width, height);
int alpha = 0xFF << 24; // 默认将bitmap当成24色图片
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
int grey = pixels[width * i + j];
int red = ((grey & 0x00FF0000) >> 16);
int green = ((grey & 0x0000FF00) >> 8);
int blue = (grey & 0x000000FF);
grey = (int) (red * 0.3 + green * 0.59 + blue * 0.11);
grey = alpha | (grey << 16) | (grey << 8) | grey;
pixels[width * i + j] = grey;
}
}
Bitmap newBmp = Bitmap.createBitmap(width, height, Config.RGB_565);
newBmp.setPixels(pixels, 0, width, 0, 0, width, height);
return newBmp;
}
/**
* 读取图片属性:图片被旋转的角度
*
* @param path 图片绝对路径
* @return 旋转的角度
*/
public static int getImageDegree(String path) {
int degree = 0;
try {
ExifInterface exifInterface = new ExifInterface(path);
int orientation = exifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
}
} catch (IOException e) {
e.printStackTrace();
}
return degree;
}
/**
* 饱和度处理
*
* @param bitmap 原图
* @param saturationValue 新的饱和度值
* @return 改变了饱和度值之后的图片
*/
public static Bitmap saturation(Bitmap bitmap, int saturationValue) {
// 计算出符合要求的饱和度值
float newSaturationValue = saturationValue * 1.0F / 127;
// 创建一个颜色矩阵
ColorMatrix saturationColorMatrix = new ColorMatrix();
// 设置饱和度值
saturationColorMatrix.setSaturation(newSaturationValue);
// 创建一个画笔并设置其颜色过滤器
Paint paint = new Paint();
paint.setColorFilter(new ColorMatrixColorFilter(saturationColorMatrix));
// 创建一个新的图片并创建画布
Bitmap newBitmap = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(newBitmap);
// 将原图使用给定的画笔画到画布上
canvas.drawBitmap(bitmap, 0, 0, paint);
return newBitmap;
}
/**
* 亮度处理
*
* @param bitmap 原图
* @param lumValue 新的亮度值
* @return 改变了亮度值之后的图片
*/
public static Bitmap lum(Bitmap bitmap, int lumValue) {
// 计算出符合要求的亮度值
float newlumValue = lumValue * 1.0F / 127;
// 创建一个颜色矩阵
ColorMatrix lumColorMatrix = new ColorMatrix();
// 设置亮度值
lumColorMatrix.setScale(newlumValue, newlumValue, newlumValue, 1);
// 创建一个画笔并设置其颜色过滤器
Paint paint = new Paint();
paint.setColorFilter(new ColorMatrixColorFilter(lumColorMatrix));
// 创建一个新的图片并创建画布
Bitmap newBitmap = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(newBitmap);
// 将原图使用给定的画笔画到画布上
canvas.drawBitmap(bitmap, 0, 0, paint);
return newBitmap;
}
/**
* 色相处理
*