BitmapUtils.java
19.1 KB
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
package com.polysoft.nafmii.utils;
import android.content.ContentResolver;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.util.Base64;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
/**
* Bitmap 工具类
*
* <p>
* 压缩算法来自luban压缩开源工具
* </p>
*
* @author zhiyuan
* @date 2018/4/17
* @see <a href="https://github.com/Curzibn/Luban">luban github文档</a>
*/
public class BitmapUtils {
private static final String TAG = "BitmapUtils";
public static String bitmap2base64(String filepath) {
Bitmap bitmap = BitmapFactory.decodeFile(filepath);
ByteArrayOutputStream baos = null;
try {
baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 95, baos);
return Base64.encodeToString(baos.toByteArray(), Base64.NO_WRAP);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != baos) {
try {
baos.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
if (null != bitmap) {
bitmap.recycle();
}
}
return "";
}
/**
* 比例压缩,具体算法来自luban压缩工具
*
* @param filepath 图片路径
* @return 压缩后的文件
*/
public static File compressBitmap(String filepath) {
File file = new File(filepath);
String newName = "temp_" + file.getName();
String newPath = new File(file.getParent(), newName).getAbsolutePath();
return compressBitmap(filepath, newPath, 95);
}
public static File compressBitmap(String filepath, String newPath) {
return compressBitmap(filepath, newPath, 95);
}
/**
* 比例压缩,具体算法来自luban压缩工具
*
* @param filepath 图片路径
* @param quality 压缩质量
* @return 压缩后的文件
*/
public static File compressBitmap(String filepath, String newPath, int quality) {
File file = new File(filepath);
if (!file.exists()) {
return file;
}
File newFile = new File(newPath);
if (null != newFile.getParentFile()) {
newFile.getParentFile().mkdirs();
}
if (newFile.exists()) {
newFile.delete();
}
int sampleSize = getSampleSize(file.getAbsolutePath());
compress(file.getAbsolutePath(), newFile.getAbsolutePath(), sampleSize, quality);
return newFile;
}
/**
* 获取压缩比例,具体算法来自luban压缩工具
*
* @return bitmap压缩比例
*/
public static int getSampleSize(String filePath) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
options.inSampleSize = 1;
BitmapFactory.decodeFile(filePath, options);
int srcWidth = options.outWidth;
int srcHeight = options.outHeight;
srcWidth = srcWidth % 2 == 1 ? srcWidth + 1 : srcWidth;
srcHeight = srcHeight % 2 == 1 ? srcHeight + 1 : srcHeight;
int longSide = Math.max(srcWidth, srcHeight);
int shortSide = Math.min(srcWidth, srcHeight);
float scale = ((float) shortSide / longSide);
if (scale <= 1 && scale > 0.5625) {
if (longSide < 1664) {
return 1;
} else if (longSide < 4990) {
return 2;
} else if (longSide < 10240) {
return 4;
} else {
return longSide / 1280 == 0 ? 1 : longSide / 1280;
}
} else if (scale <= 0.5625 && scale > 0.5) {
return longSide / 1280 == 0 ? 1 : longSide / 1280;
} else {
return (int) Math.ceil(longSide / (1280.0 / scale));
}
}
/**
* 压缩图片,使用luban算法
*
* @param filePath 图片文件地址
*/
public static void compress(String filePath, String cacheFilePath) {
compress(filePath, cacheFilePath, getSampleSize(filePath), 60);
}
/**
* 压缩图片
*
* @param filePath 图片路径
* @param cacheFilePath 缓存图片路径
* @param sampleSize 压缩比
* @param quality 质量
*/
public static void compress(String filePath, String cacheFilePath, int sampleSize, int quality) {
int degree = readPictureDegree(filePath);
//获取bitmap数据
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
bitmapOptions.inJustDecodeBounds = false;
bitmapOptions.inSampleSize = sampleSize;
Bitmap bitmap = BitmapFactory.decodeFile(filePath, bitmapOptions);
if (bitmap != null) {
if (degree > 0) {
Bitmap tempBitmap = bitmap;
Matrix matrix = new Matrix();
matrix.postRotate(degree);
bitmap = Bitmap.createBitmap(tempBitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
tempBitmap.recycle();
}
writeToFile(bitmap, cacheFilePath, Bitmap.CompressFormat.JPEG, quality);
bitmap.recycle();
}
}
/**
* Bitmap 写入文件
*
* @param bitmap bitmap
* @param cacheFilePath 文件地址
*/
public static void writeToFile(Bitmap bitmap, String cacheFilePath, Bitmap.CompressFormat compressFormat, int quality) {
if (bitmap == null) {
LogUtil.e(TAG, "尝试将空文件写入本地:bitmap " + bitmap + " cacheFilePath: "
+ cacheFilePath + " compressFormat:" + compressFormat);
return;
}
//写入原始文件
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(compressFormat, quality, bos);
File dir = new File(cacheFilePath);
File parent = dir.getParentFile();
LogUtil.i(TAG, "尝试将图片写入文件:" + dir);
if (null != parent && !parent.exists()) {
boolean succeed = parent.mkdirs();
LogUtil.i(TAG, "文件上级目录不存在,准备创建成功:" + succeed);
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(cacheFilePath);
fos.write(bos.toByteArray());
fos.flush();
bos.flush();
fos.close();
bos.close();
LogUtil.i(TAG, "文件写入成功!");
} catch (Exception e) {
LogUtil.e(TAG, "文件写入失败!" + e.getMessage());
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 压缩图片,使用谷歌压缩算法
*
* @param imagePath 需要压缩的图片路径
* @param cacheFilePath 缓存图片路径
*/
public static void zipImage(String imagePath, String cacheFilePath) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imagePath, options);
options.inSampleSize = computeInitialSampleSize(options, 480, 480 * 960);
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
try {
FileOutputStream fos = new FileOutputStream(cacheFilePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
bitmap.recycle();
bitmap = null;
System.gc();
}
private static int computeInitialSampleSize(BitmapFactory.Options options,
int minSideLength, int maxNumOfPixels) {
double w = options.outWidth;
double h = options.outHeight;
int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math
.sqrt(w * h / maxNumOfPixels));
int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(
Math.floor(w / minSideLength), Math.floor(h / minSideLength));
if (upperBound < lowerBound) {
// return the larger one when there is no overlapping zone.
return lowerBound;
}
if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
return 1;
} else if (minSideLength == -1) {
return lowerBound;
} else {
return upperBound;
}
}
public static Bitmap loadBitmap(String pathName, float ww, float hh) {
Bitmap b = null;
try {
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
b = BitmapFactory.decodeFile(pathName, opts);
int originalWidth = opts.outWidth;
int originalHeight = opts.outHeight;
// float hh = 1280f;// 这里设置高度为800f
// float ww = 720f;// 这里设置宽度为480f
// 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
int be = 1;// be=1表示不缩放
if (originalWidth > originalHeight && originalWidth > ww) {// 如果宽度大的话根据宽度固定大小缩放
be = (int) (originalWidth / ww);
} else if (originalWidth < originalHeight && originalHeight > hh) {// 如果高度高的话根据宽度固定大小缩放
be = (int) (originalHeight / hh);
}
if (be <= 0)
be = 1;
LogUtil.d("decodeFile", "originalWidth:" + originalWidth
+ ",originalHeight:" + originalHeight + ",be:" + be);
BitmapFactory.Options optso = new BitmapFactory.Options();
optso.inJustDecodeBounds = false;
optso.inPreferredConfig = Bitmap.Config.RGB_565;
optso.inSampleSize = be;
b = BitmapFactory.decodeFile(pathName, optso);
} catch (Exception e) {
e.printStackTrace();
LogUtil.e(TAG, "sdCardToByte: loadbitmap11" + e.getMessage());
b = null;
} catch (OutOfMemoryError e) {
e.printStackTrace();
LogUtil.e(TAG, "sdCardToByte: loadbitmap22" + e.getMessage());
b = null;
}
return b;
}
public static void saveBitmap(String copyfilename, Bitmap bm) {
LogUtil.e("saveBitmap", "保存图片");
File f = new File(copyfilename);
if (f.exists()) {
f.delete();
}
try {
FileOutputStream out = new FileOutputStream(f);
bm.compress(Bitmap.CompressFormat.JPEG, 70, out);
out.flush();
out.close();
LogUtil.i("saveBitmap", "已经保存");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static byte[] sdCardToByte(Context context, Uri uri, int ww, int hh) {
Bitmap bitmap = decodeUri(context, uri, ww, hh);
if (bitmap == null) return null;
LogUtil.e(TAG, "sdCardToByte: bitmap");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] byteArray = baos.toByteArray();
return byteArray;
}
public static Bitmap newLoadBitmap(Context context, String pathName, float ww, float hh) {
Bitmap b = null;
try {
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
File picture = new File(pathName);
Uri filepath = FileProviderUtils.getUriForFile(context, picture);
b = BitmapFactory.decodeFile(filepath.getPath(), opts);
int originalWidth = opts.outWidth;
int originalHeight = opts.outHeight;
int be = 1;// be=1表示不缩放
if (originalWidth > originalHeight && originalWidth > ww) {// 如果宽度大的话根据宽度固定大小缩放
be = (int) (originalWidth / ww);
} else if (originalWidth < originalHeight && originalHeight > hh) {// 如果高度高的话根据宽度固定大小缩放
be = (int) (originalHeight / hh);
}
if (be <= 0)
be = 1;
LogUtil.d("decodeFile", "originalWidth:" + originalWidth
+ ",originalHeight:" + originalHeight + ",be:" + be);
BitmapFactory.Options optso = new BitmapFactory.Options();
optso.inJustDecodeBounds = false;
optso.inPreferredConfig = Bitmap.Config.RGB_565;
optso.inSampleSize = be;
b = BitmapFactory.decodeFile(filepath.getPath(), optso);
} catch (Exception e) {
e.printStackTrace();
LogUtil.e(TAG, "sdCardToByte: loadbitmap11" + e.getMessage());
b = null;
} catch (OutOfMemoryError e) {
e.printStackTrace();
LogUtil.e(TAG, "sdCardToByte: loadbitmap22" + e.getMessage());
b = null;
}
return b;
}
/**
* 读取一个缩放后的图片,限定图片大小,避免OOM
* http://blog.sina.com.cn/s/blog_5de73d0b0100zfm8.html
*
* @param uri 图片uri,支持“file://”、“content://”
* @param maxWidth 最大允许宽度
* @param maxHeight 最大允许高度
* @return 返回一个缩放后的Bitmap,失败则返回null
*/
public static Bitmap decodeUri(Context context, Uri uri, int maxWidth, int maxHeight) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true; //只读取图片尺寸
resolveUri(context, uri, options);
//计算实际缩放比例
int scale = 1;
for (int i = 0; i < Integer.MAX_VALUE; i++) {
if ((options.outWidth / scale > maxWidth &&
options.outWidth / scale > maxWidth * 1.4) ||
(options.outHeight / scale > maxHeight &&
options.outHeight / scale > maxHeight * 1.4)) {
scale++;
} else {
break;
}
}
options.inSampleSize = scale;
options.inJustDecodeBounds = false;//读取图片内容
options.inPreferredConfig = Bitmap.Config.RGB_565; //根据情况进行修改
Bitmap bitmap = null;
try {
bitmap = resolveUriForBitmap(context, uri, options);
} catch (Throwable e) {
e.printStackTrace();
}
return bitmap;
}
// http://blog.sina.com.cn/s/blog_5de73d0b0100zfm8.html
private static void resolveUri(Context context, Uri uri, BitmapFactory.Options options) {
if (uri == null) {
return;
}
String scheme = uri.getScheme();
if (ContentResolver.SCHEME_CONTENT.equals(scheme) ||
ContentResolver.SCHEME_FILE.equals(scheme)) {
InputStream stream = null;
try {
stream = context.getContentResolver().openInputStream(uri);
BitmapFactory.decodeStream(stream, null, options);
} catch (Exception e) {
LogUtil.w("resolveUri", "Unable to open content: " + uri, e);
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
LogUtil.w("resolveUri", "Unable to close content: " + uri, e);
}
}
}
} else if (ContentResolver.SCHEME_ANDROID_RESOURCE.equals(scheme)) {
LogUtil.w("resolveUri", "Unable to close content: " + uri);
} else {
LogUtil.w("resolveUri", "Unable to close content: " + uri);
}
}
// http://blog.sina.com.cn/s/blog_5de73d0b0100zfm8.html
private static Bitmap resolveUriForBitmap(Context context, Uri uri, BitmapFactory.Options options) {
if (uri == null) {
return null;
}
Bitmap bitmap = null;
String scheme = uri.getScheme();
if (ContentResolver.SCHEME_CONTENT.equals(scheme) ||
ContentResolver.SCHEME_FILE.equals(scheme)) {
InputStream stream = null;
try {
stream = context.getContentResolver().openInputStream(uri);
bitmap = BitmapFactory.decodeStream(stream, null, options);
} catch (Exception e) {
LogUtil.w("resolveUriForBitmap", "Unable to open content: " + uri, e);
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
LogUtil.w("resolveUriForBitmap", "Unable to close content: " + uri, e);
}
}
}
} else if (ContentResolver.SCHEME_ANDROID_RESOURCE.equals(scheme)) {
LogUtil.w("resolveUriForBitmap", "Unable to close content: " + uri);
} else {
LogUtil.w("resolveUriForBitmap", "Unable to close content: " + uri);
}
return bitmap;
}
/**
* 读取照片旋转角度
*
* @param path 照片路径
* @return 角度
*/
public static int readPictureDegree(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;
}
public static byte[] bitmapToByte(Bitmap bitmap) {
ByteArrayOutputStream baos = null;
try {
baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
} finally {
IOUtils.close(baos);
}
return new byte[]{};
}
}