您的位置:首页 > 移动开发 > Android开发

Android之Bitmap使用心得(持续更新)

2012-04-26 11:28 543 查看
因为此代码里面有解释,因此直接上代码:

public class ChangeBitmapPixel extends Activity {
private Button btn;
private Bitmap photo;
private ImageView image;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
private ByteArrayOutputStream baos;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

image = (ImageView) findViewById(R.id.image);
btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
//如果使用下面注释的代码,将不返回数据给Intent
// i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment
// .getExternalStorageDirectory(),"pic.jpg")));
//启动摄像头并且在拍摄后返回
startActivityForResult(i, 10);
}});

}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//两种读取文件的方法
Uri uri = data.getData();
if (uri != null) {
System.out.println("uri不为空");
photo = BitmapFactory.decodeFile(uri.getPath());
System.out.println("uri:"+photo);
}

if (photo == null) {
Bundle bundle = data.getExtras();
if (bundle != null) {
photo = (Bitmap) bundle.get("data");
image.setImageBitmap(photo);
//保存照片
savePic(photo);
System.out.println("photo:"+photo);
} else {
Toast.makeText(ChangeBitmapPixel.this,
"为空",
Toast.LENGTH_LONG).show();
return;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public void savePic(Bitmap bitmap){
//使用此流读取
baos = new ByteArrayOutputStream();
//第二个参数影响的是图片的质量,但是图片的宽度与高度是不会受影响滴
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos);
//这个函数能够设定图片的宽度与高度
//Bitmap map = Bitmap.createScaledBitmap(bitmap, 400, 400, true);
//把数据转为为字节数组
byte[] byteArray = baos.toByteArray();
try {
fos = new FileOutputStream(Environment.getExternalStorageDirectory()+"pic.jpg");
bos = new BufferedOutputStream(fos);
bos.write(byteArray);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
baos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: