安卓头像.本地获取图片和拍照

来源:互联网 发布:曼陀罗训练软件 编辑:程序博客网 时间:2024/05/03 15:48

1.用的是starActivityforresult

case R.id.ll_my_im:
startActivityPhoto();


break;


}
}


private void startActivityPhoto() {
Intent photo=new Intent(getActivity(),MyPhotoActivity.class);
startActivityForResult(photo, SHOW_MY_PHOTO);

}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode==1&&resultCode==-1) {
if (data!=null) {
byte[] bis = data.getByteArrayExtra("bitmap");
BitmapFactory.Options opts=new BitmapFactory.Options();
opts.inSampleSize=2;
opts.inPreferredConfig=Config.ARGB_4444;
Bitmap bitmap = BitmapFactory.decodeByteArray(bis, 0, bis.length, opts);
myphoto.setImageBitmap(bitmap);

try {
saveMyBitmap("myphoto", bitmap);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}
}
public void saveMyBitmap(String bitName,Bitmap mBitmap) throws IOException {  
        File f = new File("/sdcard/Note/" + bitName);  
        if(!f.exists())  
            f.mkdirs();//如果没有这个文件夹的话,会报file not found错误  
        f=new File("/sdcard/Note/"+bitName+".png");  
        f.createNewFile();  
        try {  
            FileOutputStream out = new FileOutputStream(f);  
             mBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);  
             out.flush();  
             out.close();  
        } catch (FileNotFoundException e) {  
        }  
         
    }  





2.另一个Activity



import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;


import cn.wudao.recreation.activity.BaseActivity;
import cn.wudao.recreation.fragment.MyFragment;


import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;


public class MyPhotoActivity extends BaseActivity {




private ImageView imageView;//图片 
private Button clickBtnLocal;//本地图片
private Button clickBtnCamera;//拍摄图片的按钮
private Button savephoto;


private Uri photoUri;//


private final int PIC_FROM_CAMERA = 1;
private final int PIC_FROM_LOCALPHOTO = 0;

public static final int RESULT_OK = -1;
private  Bitmap entity;
private byte[] bitmapByte;
private Handler handler=new Handler(){






public void handleMessage(android.os.Message msg) {


entity=(Bitmap) msg.obj;
if (entity!=null) {
//把bitmap变成字节数组
ByteArrayOutputStream out=new ByteArrayOutputStream();  
entity.compress(CompressFormat.JPEG, 100, out);
bitmapByte =out.toByteArray();  
      try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return;


};
};




@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_photo);
//初始化控件
imageView = (ImageView) findViewById(R.id.image);
clickBtnLocal = (Button) findViewById(R.id.click_local);
clickBtnCamera = (Button) findViewById(R.id.click_camera);
savephoto=(Button) findViewById(R.id.save);


//本地选择
clickBtnLocal.setOnClickListener(new View.OnClickListener() 
{
@Override
public void onClick(View v) 
{
doHandlerPhoto(PIC_FROM_LOCALPHOTO);// 从相册中去获取
}
});


//拍照
clickBtnCamera.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) 
{
doHandlerPhoto(PIC_FROM_CAMERA);// 用户点击了从照相机获取
}
});


}


public void doClick(View view){
switch (view.getId()) {
case R.id.save:
Intent intent=new Intent();
intent.putExtra("bitmap", bitmapByte);
//设置返回数据
MyPhotoActivity.this.setResult(RESULT_OK, intent);
//关闭Activity
MyPhotoActivity.this.finish();



// Intent intent=new Intent();
// Bundle bundle = new Bundle();
// //把Bitmap对象放到bundle中
// bundle.putParcelable("bitmap", entity);
// //通过Intent来传递Bundle
// intent.putExtra("bundle", bundle);
// MyPhotoActivity.this.setResult(RESULT_OK, intent);
// MyPhotoActivity.this.finish();
break;



}
}


/**
* 根据不同方式选择图片设置ImageView
* @param type 0-本地相册选择,非0为拍照
*/
private void doHandlerPhoto(int type)
{
try
{
//保存裁剪后的图片文件 //new一个文件路径  如果这个问价夹不存在的话就去创建一个
File pictureFileDir = new File(Environment.getExternalStorageDirectory(), "/upload");
//这里的是创建文件目录
if (!pictureFileDir.exists()) {
pictureFileDir.mkdirs();
}//把这个文件 放在这个文件夹中 然后看picfile存在不存在 不存在去创建一个


//createNewFile()创建文件,指定mkdir()时创建目录
File picFile = new File(pictureFileDir, "upload.jpeg");
if (!picFile.exists()) {
picFile.createNewFile();
}


//相当于保存的路径
photoUri = Uri.fromFile(picFile);
//如果这个类型是本地的
if (type==PIC_FROM_LOCALPHOTO)
{
Intent intent = getCropImageIntent();
startActivityForResult(intent, PIC_FROM_LOCALPHOTO);
}else
{ //否则就是拍照的
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
startActivityForResult(cameraIntent, PIC_FROM_CAMERA);
}


} catch (Exception e)
{
Log.i("HandlerPicError", "处理图片出现错误");
}
}


/**
* 调用图片剪辑程序
*/
public Intent getCropImageIntent() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
intent.setType("image/*");
setIntentParams(intent);
return intent;
}


/**
* 启动裁剪
*/
private void cropImageUriByTakePhoto() {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(photoUri, "image/*");
setIntentParams(intent);
startActivityForResult(intent, PIC_FROM_LOCALPHOTO);
}


/**
* 设置公用参数  图片剪切的公式
*/
private void setIntentParams(Intent intent)
{
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 600);
intent.putExtra("outputY", 600);
intent.putExtra("noFaceDetection", true); // no face detection
intent.putExtra("scale", true);
intent.putExtra("return-data", false);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{ //请求吗
switch (requestCode)
{
case PIC_FROM_CAMERA: // 拍照
try 
{
cropImageUriByTakePhoto();
} catch (Exception e) 
{
e.printStackTrace();
}
break;
case PIC_FROM_LOCALPHOTO://本地
try
{
if (photoUri != null) 
{
Bitmap bitmap = decodeUriAsBitmap(photoUri);//根据路径把图片取出来 转化成bitmap然后显示
imageView.setImageBitmap(bitmap);
Message msg=Message.obtain();
msg.obj=bitmap;
handler.sendMessage(msg);


}
} catch (Exception e) 
{
e.printStackTrace();
}
break;
}
}


private Bitmap decodeUriAsBitmap(Uri uri)
{
Bitmap bitmap = null;
try 
{ //根据内容提供者把uri取出来
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
} catch (FileNotFoundException e)
{
e.printStackTrace();
return null;
}
return bitmap;
}

}







0 0
原创粉丝点击