-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompressBitmap.java
More file actions
69 lines (52 loc) · 1.66 KB
/
Copy pathCompressBitmap.java
File metadata and controls
69 lines (52 loc) · 1.66 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
package com.example.kongalong.ximalaya_mvp.imageLoad;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
/**
*
* 图片压缩
*
* Created by kongalong on 2016/11/7.
*/
public class CompressBitmap {
/**
* @param bytes 数据源是byte[]
* @param width
* @param height
* @return
*/
public static Bitmap compressFromBytes(byte[] bytes,int width, int height){
if(width==-1||height==-1){
return BitmapFactory.decodeByteArray(bytes,0,bytes.length);
}
//
if(bytes==null){
return null;
}
BitmapFactory.Options option = new BitmapFactory.Options();
//第一次采样
option.inJustDecodeBounds = true;
Bitmap bitmapNull = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, option);
//根据采样结果按比例计算最终大小
option.inSampleSize = calculateSize(option,width,height);
//二次采样
option.inJustDecodeBounds = false;
//返回最终bitmap
return BitmapFactory.decodeByteArray(bytes,0,bytes.length,option);
}
//根据采样结果按比例计算最终大小
private static int calculateSize(BitmapFactory.Options option, int width, int height) {
//初始化比例
int sampleSize = 1;
//获取原始大小
int RawWidth = option.outWidth;
int RawHeight = option.outHeight;
//获取倍数
int w = width / RawWidth;
int h = height / RawHeight;
//计算比例
while(sampleSize <= w || sampleSize <= h){
sampleSize *= 2;
}
return sampleSize;
}
}