从相机捕获失败

时间:2016-05-11 13:59:47

标签: android android-fragments android-camera

我想制作照片并在新活动中展示, 但我得到了烤面包“捕获失败”。日志看起来像是有序的。 你可以在方法onActivityResult上找到这个吐司。

public class FragmentScaling extends Fragment implements View.OnClickListener{

Button btnCamera, btnGallery;
private static final int PHOTO_INTENT_REQUEST_CODE = 100;
private static final int GALLERY_INTENT_REQUEST_CODE = 1;
public Uri uri;

public FragmentScaling() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_scaling, container, false);
    btnCamera = (Button) view.findViewById(R.id.b_camera);
    btnGallery = (Button) view.findViewById(R.id.b_gallery);
    btnCamera.setOnClickListener(this);
    btnGallery.setOnClickListener(this);
    uri = generateFileUri();

    return view;
}

@Override
public void onClick(View v) {
    switch (v.getId()){
        //если выбрали камеру - запускаем ее
        case R.id.b_camera:
            //uri = generateFileUri();
            if (uri == null) {
                Toast.makeText(getView().getContext(), getResources().getString(R.string.sdnot), Toast.LENGTH_LONG).show();
                return;
            }
            Intent intentCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            //intentCamera.putExtra("return-data", true);
            startActivityForResult(intentCamera, PHOTO_INTENT_REQUEST_CODE);
        break;

    }
}

//получаем результат из галереи или камеры
@Override
public void onActivityResult(int requestCode, int resultCode, Intent imageReturned) {

    switch (requestCode) {

        //если результат пришел от камеры
        case PHOTO_INTENT_REQUEST_CODE:
            if (resultCode == getActivity().RESULT_OK) {
                Log.i("HHHHHHHHHHHH", "result ok");
                //извлекаем uri фотки из интента
                Uri selectedImage = uri;
                Log.i("HHHHHHHHHHHH", "getdata works!");
                //создаем интент для запуска новой активити
                Intent last_intent_photo = new Intent(getView().getContext(), ViewPhoto.class);
                //помещаем в интент этот uri
                last_intent_photo.putExtra("fotka", selectedImage);
                //стартуем новую активити
                startActivity(last_intent_photo);

            } else if (resultCode == getActivity().RESULT_CANCELED)
                Toast.makeText(getView().getContext(), "Capture cancelled", Toast.LENGTH_LONG).show();
            else
                Toast.makeText(getView().getContext(), "Capture failed", Toast.LENGTH_LONG).show();
                break;
        default: super.onActivityResult(requestCode, resultCode, imageReturned);

    }
}

private Uri generateFileUri() {
    // Проверяем доступность SD карты
    if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
        return null;

    // Проверяем и создаем директорию
    File path = new File (Environment.getExternalStorageDirectory(), "CameraTest");
    if (! path.exists()){
        if (! path.mkdirs()){
            return null;
        }
    }

    // Создаем имя файла
    String timeStamp = String.valueOf(System.currentTimeMillis());
    File newFile = new File(path.getPath() + File.separator + timeStamp + ".jpg");
    return Uri.fromFile(newFile);
}

// Save the activity state when it's going to stop.
@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    if (uri != null) {
        outState.putString("uri", uri.toString());
    }
}

// Recover the saved state when the activity is recreated.
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    if (getActivity().getIntent().hasExtra("uri")) {
            uri = (Uri)getActivity().getIntent().getParcelableExtra("uri");
        }
    }
}

我非常希望得到你的帮助。 请不要踢我。我很难学习)))

public class ViewPhoto extends Activity {

    private ZoomControls zoom;
    CustomImageVIew imageView;

    private float scaleWidth = 1;
    private float scaleHeight = 1;
    private Bitmap bmp;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_photo_layout);

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);

        imageView = (CustomImageVIew)findViewById(R.id.customImageVIew);

        zoom = (ZoomControls) findViewById(R.id.zoomControls);

        //получаем интент, достаем из него фотку и ставим в имиджвью
        Intent intent = getIntent();
        Uri uri = (Uri) intent.getExtras().getParcelable("fotka");
        try {
            bmp = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), uri);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //imageView.setImageURI(uri);

        // увеличение
        zoom.setOnZoomInClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                int bmpWidth = bmp.getWidth();
                int bmpHeight = bmp.getHeight();

                double scale = 1.25;

                scaleWidth = (float) (scaleWidth * scale);
                scaleHeight = (float) (scaleHeight * scale);

                Matrix matrix = new Matrix();
                matrix.postScale(scaleWidth, scaleHeight);
                Bitmap resizeBmp = Bitmap.createBitmap(bmp, 0, 0, bmpWidth,
                        bmpHeight, matrix, true);
                imageView.setImageBitmap(resizeBmp);
            }
        });

        // уменьшение
        zoom.setOnZoomOutClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                int bmpWidth = bmp.getWidth();
                int bmpHeight = bmp.getHeight();

                double scale = 0.8;

                scaleWidth = (float) (scaleWidth * scale);
                scaleHeight = (float) (scaleHeight * scale);

                Matrix matrix = new Matrix();
                matrix.postScale(scaleWidth, scaleHeight);
                Bitmap resizeBmp = Bitmap.createBitmap(bmp, 0, 0, bmpWidth,
                        bmpHeight, matrix, true);
                imageView.setImageBitmap(resizeBmp);
            }
        });
    }

Class public class ViewPhoto extends Activity {

    private ZoomControls zoom;
    CustomImageVIew imageView;

    private float scaleWidth = 1;
    private float scaleHeight = 1;
    private Bitmap bmp;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_photo_layout);

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);

        imageView = (CustomImageVIew)findViewById(R.id.customImageVIew);

        zoom = (ZoomControls) findViewById(R.id.zoomControls);

        //получаем интент, достаем из него фотку и ставим в имиджвью
        Intent intent = getIntent();
        Uri uri = (Uri) intent.getExtras().getParcelable("fotka");
        try {
            bmp = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), uri);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //imageView.setImageURI(uri);

        // увеличение
        zoom.setOnZoomInClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                int bmpWidth = bmp.getWidth();
                int bmpHeight = bmp.getHeight();

                double scale = 1.25;

                scaleWidth = (float) (scaleWidth * scale);
                scaleHeight = (float) (scaleHeight * scale);

                Matrix matrix = new Matrix();
                matrix.postScale(scaleWidth, scaleHeight);
                Bitmap resizeBmp = Bitmap.createBitmap(bmp, 0, 0, bmpWidth,
                        bmpHeight, matrix, true);
                imageView.setImageBitmap(resizeBmp);
            }
        });

        // уменьшение
        zoom.setOnZoomOutClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                int bmpWidth = bmp.getWidth();
                int bmpHeight = bmp.getHeight();

                double scale = 0.8;

                scaleWidth = (float) (scaleWidth * scale);
                scaleHeight = (float) (scaleHeight * scale);

                Matrix matrix = new Matrix();
                matrix.postScale(scaleWidth, scaleHeight);
                Bitmap resizeBmp = Bitmap.createBitmap(bmp, 0, 0, bmpWidth,
                        bmpHeight, matrix, true);
                imageView.setImageBitmap(resizeBmp);
            }
        });
    }

类公共类ViewPhoto扩展了Activity {

private ZoomControls zoom;
CustomImageVIew imageView;

private float scaleWidth = 1;
private float scaleHeight = 1;
private Bitmap bmp;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.view_photo_layout);

    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);

    imageView = (CustomImageVIew)findViewById(R.id.customImageVIew);

    zoom = (ZoomControls) findViewById(R.id.zoomControls);

    //получаем интент, достаем из него фотку и ставим в имиджвью
    Intent intent = getIntent();
    Uri uri = (Uri) intent.getExtras().getParcelable("fotka");
    try {
        bmp = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), uri);
    } catch (IOException e) {
        e.printStackTrace();
    }
    //imageView.setImageURI(uri);

    // увеличение
    zoom.setOnZoomInClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            int bmpWidth = bmp.getWidth();
            int bmpHeight = bmp.getHeight();

            double scale = 1.25;

            scaleWidth = (float) (scaleWidth * scale);
            scaleHeight = (float) (scaleHeight * scale);

            Matrix matrix = new Matrix();
            matrix.postScale(scaleWidth, scaleHeight);
            Bitmap resizeBmp = Bitmap.createBitmap(bmp, 0, 0, bmpWidth,
                    bmpHeight, matrix, true);
            imageView.setImageBitmap(resizeBmp);
        }
    });

    // уменьшение
    zoom.setOnZoomOutClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            int bmpWidth = bmp.getWidth();
            int bmpHeight = bmp.getHeight();

            double scale = 0.8;

            scaleWidth = (float) (scaleWidth * scale);
            scaleHeight = (float) (scaleHeight * scale);

            Matrix matrix = new Matrix();
            matrix.postScale(scaleWidth, scaleHeight);
            Bitmap resizeBmp = Bitmap.createBitmap(bmp, 0, 0, bmpWidth,
                    bmpHeight, matrix, true);
            imageView.setImageBitmap(resizeBmp);
        }
    });
}

CustomImageVIew扩展了ImageView并实现了多点触控。

view_photo_layout.xml

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ZoomControls
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/zoomControls"
        android:layout_gravity="center_horizontal|bottom"
        android:layout_margin="5dp" />

    <ru.bunakov.testapplication.CustomImageVIew
        android:id="@+id/customImageVIew"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="5dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="5dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:scaleType="matrix"/>
</FrameLayout>

1 个答案:

答案 0 :(得分:1)

您是否添加了权限?

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

要恢复uri,请使用此方法

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    if (savedInstanceState != null && savedInstanceState.containsKey("uri")) {
        uri = Uri.parse(savedInstanceState.getString("uri"));
    }
}