Android學習之呼叫系統相機拍照、截圖並儲存

紫霧凌寒發表於2015-11-18
版權宣告:本文為博主原創文章,轉載請註明出處http://blog.csdn.net/u013132758。 https://blog.csdn.net/u013132758/article/details/49912643

最近寫一款拍照的APP用到了拍照,截圖,並返回ImageView。網上找了好幾種fang法,發現最好還是呼叫系統自帶的,既簡單又方便。

啟用android 系統相機

intent =new
Intent(MediaStore.ACTION_IMAGE_CAPTURE);

啟用android截圖

intent = new Intent("com.android.camera.action.CROP");//動作-裁剪

下面是我的程式碼

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Environment;
import android.provider.MediaStore;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.net.Uri;

import android.widget.TextView;
import android.widget.Toast;
import com.soundcloud.android.crop.Crop;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


import me.qincai.newton.R;
import me.qincai.newton.listener.NavigationFinishClickListener;
import me.qincai.newton.util.Utils;


public class MainActivity extends AppCompatActivity implements Toolbar.OnMenuItemClickListener {

    private static final int REQUEST_IMAGE_CAPTURE = 330;
    private static File photoFile;
    private static File cropFile;
    public static String crop;
    public static String crop1;
    @Bind(R.id.main_toolbar)
    protected Toolbar toolbar;

    @Bind(R.id.tv_register)
    protected TextView tv_register;

    @Bind(R.id.btn_capture)
    protected com.rey.material.widget.Button btn_capture;

    private static final int REQUEST_CROP = 332;
    public static final int REQUEST_LOGIN = 331;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        toolbar.setNavigationOnClickListener(new NavigationFinishClickListener(this));
        toolbar.inflateMenu(R.menu.menu_main);
        toolbar.setOnMenuItemClickListener(this);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
    @Override
    public boolean onMenuItemClick(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        switch (id) {
            case R.id.action_user:
                if (Utils.isLogin()) {
                    Intent intent = new Intent(MainActivity.this, ProfileActivity.class);
                    startActivity(intent);
                } else {
                    Utils.loginRequired(MainActivity.this);
                }
                return true;
            case R.id.action_questions:
                Intent intent = new Intent(MainActivity.this, QuestionsActivity.class);
                startActivity(intent);
                return true;
            default:
                return false;
        }
    }
    @OnClick(R.id.btn_capture)
    public void onCapture() {
        // 未登陸則引導登陸
        if (!Utils.isLogin()) {
            Utils.loginRequired(MainActivity.this);
        } else {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (intent.resolveActivity(getPackageManager()) != null) {
                try {
                    photoFile = createImageFile();
                } catch (IOException e) {
                    Toast.makeText(this, "寫入圖片出錯", Toast.LENGTH_SHORT).show();
                }
                if (photoFile != null) {
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                    startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (data == null)
        if (resultCode != RESULT_OK)
            return;
        switch (requestCode) {
            case REQUEST_IMAGE_CAPTURE:
                Uri u = Uri.fromFile(photoFile);
                cropPhoto(u);
                break;
            case REQUEST_CROP:
                Log.e("截圖成功onActivityResult", "data is " + data.toString());
                handleCrop();
                break;
            case REQUEST_LOGIN:
                break;
        }
    }

    public void cropPhoto(Uri uri) {
        try {
            cropFile = createImageFile();
        }catch (IOException e)
        {
            Log.e("jianliwenjiancuowu","sedfwedf");
        }

        if (uri == null) {
            return;
        }
        Intent intent = new Intent("com.android.camera.action.CROP");//動作-裁剪
        intent.setDataAndType(uri, "image/*");//型別
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cropFile));//// 輸出檔案
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());// 輸出格式
        intent.putExtra("crop", true);
        intent.putExtra("scale", true);// 縮放
        intent.putExtra("scaleUpIfNeeded", true);// 如果小於要求輸出大小,就放大
        intent.putExtra("return-data", false);// 不返回縮圖
        intent.putExtra("noFaceDetection", true);// 關閉人臉識別
        startActivityForResult(intent,REQUEST_CROP);
    }
    private void handleCrop() {
        Intent intent = new Intent(MainActivity.this, PreviewActivity.class);
        intent.putExtra("image_cropped_file", cropFile.toString());
        startActivity(intent);
    }

    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(new Date());
        String imageFileName = "QC_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );
        // Save a file: path for use with ACTION_VIEW intents
        return image;
    }

    @OnClick(R.id.tv_register)
    protected void onRegisterClick() {
        Intent intent = new Intent(MainActivity.this, RegisterActivity.class);
        startActivity(intent);
    }
}

這就是簡單的呼叫系統相機,如果大家有興趣想自定義一個相機的話,可以看一看我的這篇部落格:【Android 開發】SufaceView自定義相機拍照


相關文章