Android实现拍照,以及从相册选择图片裁剪功能同时保存在本地

时间:2022-11-01 12:19:42


       首先,我本人以前没接触过Android又是刚工作一段时间,前段时间比较忙,今天来跟大家分享下最近的收获吧,最近项目中需要一个拍照以及修剪图片,并保存修剪之后的图片到相对应的位置区,我们直接进入主题哈。不对的地方多多指教,勿喷。

<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:background="@android:color/white"
     android:orientation="vertical" >
  <LinearLayout
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:gravity="center"
         >
        <ImageView
         android:id="@+id/image"
         android:layout_width="70dp"
         android:layout_height="100dp"
         android:src="@drawable/qzx"/>
 </LinearLayout>
      <Button
         android:id="@+id/toCamera"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:padding="10dp"
         android:text="拍照" />
         <Button
         android:id="@+id/toSelectPhoto"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:padding="10dp"
         android:text="相册" />
       <Button
         android:id="@+id/uplodphoto"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:padding="10dp"
         android:text="上传" />

</LinearLayout>

首先呢这是前台的一个布局,我相信大家都能看懂。我们通过按钮拍照,就可以调用拍照的功能啦,


 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_onphoto);//这里呢是指向那个拍照的前台界面 也就是上面的布局
   takephoto=(Button)findViewById(R.id.toCamera);//这里是调用拍照那个button

   selectphoto=(Button) findViewById(R.id.toSelectPhoto);//同理 选择相册
   takephoto.setOnClickListener(listener);//listener 当然了这个是个监听啦

   selectphoto.setOnClickListener(listener);
    upload.setOnClickListener(listener);
    PortableSystemApplication gisQueryApplication = (PortableSystemApplication) this.getApplication();
    gisQueryApplication.addActivity(this);
    this.mHandler = new MyHandler(Looper.myLooper());
    imageView=(ImageView)findViewById(R.id.image);
   }
   private OnClickListener listener=new OnClickListener(){
    @Override
    public void onClick(View v) {
     switch (v.getId()) {
     case R.id.toCamera:
      OnPhotoActivity.this.onPhoto();
      break;
     case R.id.toSelectPhoto:
      pickPhoto();
      break;
     case R.id.uplodphoto:
      if(!uploadphoto.equals(""))
      {
       upload.setEnabled(false);
       onPreExecute();
       UploadThread uploadThread = new UploadThread();
       new Thread(uploadThread).start();
      }else{
       Toast.makeText(OnPhotoActivity.this, "请选择图片", Toast.LENGTH_SHORT).show(); 
       return;
      }
      break;
     }
    }
   };

下面使我们具体调用拍照功能的代码了;

protected void onPhoto() {
    if (Environment.getExternalStorageState().equals("mounted")) {    //判断sd卡是否存在
    String str1 =((PortableSystemApplication) this.getApplication()).getProjectPath()+ "CameraPhoto/";
     String str2 = UtilsTools.GetCurrentTime() + ".jpg";
     File localFile = new File(str1);
     if (!(localFile.exists()))
      localFile.mkdirs();
     m_CurrentCamaraPath  = str1 + str2;
     m_CurrentCamaraPhotoName = str2;
     Log.i("拍照1", "路径=" + m_CurrentCamaraPath);
     Log.i("拍照1", "名字=" + m_CurrentCamaraPhotoName);
     Uri localUri = Uri.fromFile(new File(str1, str2));
     Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
     intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
       str1, str2)));
     startActivityForResult(intent, PHOTO_GRAPH);
     Log.i("OnPhotoActivity.this.m_CurrentCamaraPath", "=========="+m_CurrentCamaraPath);
    } else {
     Toast.makeText(this, "无SD卡", 1).show();
    } 
   }


这部分代码的实现从相册选择;


 protected void pickPhoto() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT); 
    startActivityForResult(intent, PHOTO_ZOOM);
   }

这部分是实现裁剪的;

public void startPhotoZoom(Uri uri) {
            Intent intent = new Intent("com.android.camera.action.CROP");
            intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
            intent.putExtra("crop", "true");
            // aspectX aspectY 是宽高的比例
           intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            // outputX outputY 是裁剪图片宽高
           intent.putExtra("outputX", 300);
            intent.putExtra("outputY", 500);
            intent.putExtra("return-data", true);
            OnPhotoActivity.this.startActivityForResult(intent, PHOTO_RESOULT);
        } 

下面是调用拍照返回来的一些参数

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     if (resultCode == NONE)
      return;
     if (requestCode == PHOTO_GRAPH) {
                // 设置文件保存路径
     if(!m_CurrentCamaraPath.equals("")){
       File picture = new File(m_CurrentCamaraPath);
       startPhotoZoom(Uri.fromFile(picture));
      }else{
       Toast.makeText(this, "m_CurrentCamaraPath 为“”", 1).show();
      }
     }
     if(data == null)
     {
      return;
     }
     if(requestCode == PHOTO_ZOOM )  //从相册取图片,有些手机有异常情况,请注意
    {
      startPhotoZoom(data.getData());
     }
            // 处理结果
    if (requestCode == PHOTO_RESOULT) {
      if (data != null) {
       Bitmap bitmap = data.getParcelableExtra("data");
       imageView.setImageBitmap(bitmap); //把图片显示在ImageView控件上
      SavePicInLocal( bitmap);
      }
      try {
        // 将临时文件删除
      picture.delete();
      } catch (Exception e) {
       e.printStackTrace();
      }
     }
     super.onActivityResult(requestCode, resultCode, data);
    }


这个是将裁剪返回的数据保存

 private void SavePicInLocal(Bitmap bitmap) {
      FileOutputStream fos = null;
      BufferedOutputStream bos = null;
      ByteArrayOutputStream baos = null; // 字节数组输出流
     try {
       baos = new ByteArrayOutputStream();
       bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
       byte[] byteArray = baos.toByteArray();// 字节数组输出流转换成字节数组
       String patch =((PortableSystemApplication) this.getApplication()).getProjectPath()+ "CameraPhoto/";
       String picName = UtilsTools.GetCurrentTime() + ".jpg";
      // String picName =m_CurrentCamaraPhotoName;
       uploadphoto=patch+picName;
       File file = new File(patch, picName);
       // 将字节数组写入到刚创建的图片文件中
      fos = new FileOutputStream(file);
       bos = new BufferedOutputStream(fos);
       bos.write(byteArray);
      } catch (Exception e) {
       e.printStackTrace();
      } finally {
       if (baos != null) {
        try {
         baos.close();
        } catch (Exception e) {
         e.printStackTrace();
        }
       }
       if (bos != null) {
        try {
         bos.close();
        } catch (Exception e) {
         e.printStackTrace();
        }
       }
       if (fos != null) {
        try {
         fos.close();
        } catch (Exception e) {
         e.printStackTrace();
        }
       }
      }
    }