在安卓系统中,照片的大小是根据摄像头的分辨率而定的,一般是分辨率X4,就是照片的大。由于安卓系统中规定照片大小不能超过16M,因此,如果直接将照片存入内存,会造成OOM(内存溢出),故采用二次采样的方式对照片进行存储。
1.直接取系统已经压缩过的缩略图:
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView= (ImageView) findViewById(R.id.imageView);
}
public void open(View v){
Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,0);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==0&&resultCode==RESULT_OK){
Bitmap bitmap=data.getParcelable("data);
imageView.setImageBitmap(bitmap);
}
}
}
2.通过二次采样,二次采样的原理如下:
2.1.第一次,先取出图片的宽高,不取它的真实大小,因此bitmap是空的;
2.2.第二次,取出它的大小,并进行压缩处理。
代码:
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
private File file;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView= (ImageView) findViewById(R.id.imageView);
file=new File(Environment.getExternalStorageDirectory(),"text.jpg");
}
public void open(View v){
Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(intent,0);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==0&&resultCode==RESULT_OK){
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds=true;
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(),options);
options.inPreferredConfig= Bitmap.Config.RGB_565;
将边框缩减到原来宽高的1/100;
options.inSampleSize=Math.max(options.outWidth,options.outHeight)/100;
设置为false,表示不仅仅加载边框,
options.inJustDecodeBounds=false;
bitmap=BitmapFactory.decodeFile(file.getAbsolutePath(),options);
Toast.makeText(MainActivity.this, options.outWidth+"X"+options.outHeight, Toast.LENGTH_SHORT).show();
imageView.setImageBitmap(bitmap);
}
}
}
- 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
这样,就OK了!