通过MediaStore打开相机时,在SD卡上保存了空白(0kb)文件.ACTION_IMAGE_CAPTURE

时间:2013-04-03 12:37:01

标签: android file android-camera android-camera-intent

使用MediaStore.ACTION_IMAGE_CAPTURE intent打开相机时。即使我不保存图像或丢弃图像或只是返回,它也会在SD卡中保存0kb或空白文件,即使我没有保存图像。 >编辑::但如果我保存图像,它会保存正确的图像 .Below是我正在处理的代码:

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

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PointF;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.FloatMath;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.VideoView;


public class DocsAdd extends Activity 
{

    private static final int ACTION_TAKE_PHOTO_B = 1;


    private static final String BITMAP_STORAGE_KEY = "viewbitmap";
    private static final String IMAGEVIEW_VISIBILITY_STORAGE_KEY = "imageviewvisibility";
    private ImageView mImageView;
    private Bitmap mImageBitmap;



    private String mCurrentPhotoPath;

    private static final String JPEG_FILE_PREFIX = "IMG_";
    private static final String JPEG_FILE_SUFFIX = ".jpg";


    private File getAlbumDir() 
    {

        Log.i("inside ", "docs add");
        String path = Environment.getExternalStorageDirectory().toString();          
        File filenamedemo = new File(path + "/AutoistDiary/ImageFolder/");

        String name=String.valueOf(filenamedemo);
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) 
        {

            if (name != null) 
            {
                if (! filenamedemo.mkdirs()) 
                {
                    if (! filenamedemo.exists())
                    {
                        Log.d("CameraSample", "failed to create directory");
                        return null;
                    }
                }
            }

        } else {

        }

        return filenamedemo;
    }

    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
        File albumF = getAlbumDir();
        File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX, albumF);
        return imageF;
    }

    private File setUpPhotoFile() throws IOException {

        File f = createImageFile();
        mCurrentPhotoPath = f.getAbsolutePath();

        return f;
    }


    private void galleryAddPic() {
            Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
            File f = new File(mCurrentPhotoPath);
            Uri contentUri = Uri.fromFile(f);
            mediaScanIntent.setData(contentUri);
            this.sendBroadcast(mediaScanIntent);
    }

    private void dispatchTakePictureIntent() {

        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);


            File f = null;

            try {
                f = setUpPhotoFile();
                mCurrentPhotoPath = f.getAbsolutePath();
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
            } catch (IOException e) {
                e.printStackTrace();
                f = null;
                mCurrentPhotoPath = null;
            }

        startActivityForResult(takePictureIntent,0);
    }



private void handleBigCameraPhoto() 
    {

        if (mCurrentPhotoPath != null) 
        {
            //setPic();
            galleryAddPic();
            mCurrentPhotoPath = null;

            Intent viewint=new Intent(DocsAdd.this, DocsShow.class);        
            Log.i("calling ", "view activity");
            startActivity(viewint);
            finish();
        }

    }


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        dispatchTakePictureIntent();

        /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
            mAlbumStorageDirFactory = new FroyoAlbumDirFactory();
        } else {
            mAlbumStorageDirFactory = new BaseAlbumDirFactory();
        }*/
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    {
        handleBigCameraPhoto(); 
    }

    // Some lifecycle callbacks so that the image can survive orientation change
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putParcelable(BITMAP_STORAGE_KEY, mImageBitmap);

        outState.putBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY, (mImageBitmap != null) );

        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState)
    {
        super.onRestoreInstanceState(savedInstanceState);
        mImageBitmap = savedInstanceState.getParcelable(BITMAP_STORAGE_KEY);
        mImageView.setImageBitmap(mImageBitmap);
        mImageView.setVisibility(
                savedInstanceState.getBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY) ? 
                        ImageView.VISIBLE : ImageView.INVISIBLE
        );

    }

    /**
     * Indicates whether the specified action can be used as an intent. This
     * method queries the package manager for installed packages that can
     * respond to an intent with the specified action. If no suitable package is
     * found, this method returns false.
     * http://android-developers.blogspot.com/2009/01/can-i-use-this-intent.html
     *
     * @param context The application's environment.
     * @param action The Intent action to check for availability.
     *
     * @return True if an Intent with the specified action can be sent and
     *         responded to, false otherwise.
     */
    public static boolean isIntentAvailable(Context context, String action) 
    {
        final PackageManager packageManager = context.getPackageManager();
        final Intent intent = new Intent(action);
        List<ResolveInfo> list =packageManager.queryIntentActivities(intent,PackageManager.MATCH_DEFAULT_ONLY);
        return list.size() > 0;
    }

     /** Show an event in the LogCat view, for debugging */
    private void dumpEvent(MotionEvent event) {
       String names[] = { "DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE",
             "POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" };
       StringBuilder sb = new StringBuilder();
       int action = event.getAction();
       int actionCode = action & MotionEvent.ACTION_MASK;
       sb.append("event ACTION_").append(names[actionCode]);
       if (actionCode == MotionEvent.ACTION_POINTER_DOWN
             || actionCode == MotionEvent.ACTION_POINTER_UP) {
          sb.append("(pid ").append(
                action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
          sb.append(")");
       }
       sb.append("[");
       for (int i = 0; i < event.getPointerCount(); i++) {
          sb.append("#").append(i);
          sb.append("(pid ").append(event.getPointerId(i));
          sb.append(")=").append((int) event.getX(i));
          sb.append(",").append((int) event.getY(i));
          if (i + 1 < event.getPointerCount())
             sb.append(";");
       }
       sb.append("]");

    }


    /** Determine the space between the first two fingers */
    private float spacing(MotionEvent event) {
       float x = event.getX(0) - event.getX(1);
       float y = event.getY(0) - event.getY(1);
       return FloatMath.sqrt(x * x + y * y);
    }

    /** Calculate the mid point of the first two fingers */
    private void midPoint(PointF point, MotionEvent event) {
       float x = event.getX(0) + event.getX(1);
       float y = event.getY(0) + event.getY(1);
       point.set(x / 2, y / 2);
    }

    public void onCancel() 
    {
        // TODO Auto-generated method stub
        Log.i("on click", "discard image");
        Log.d("on click", "discard image hahahahahaaaaaa");
    }
}

任何人都可以指出为什么会保存空白文件或者可以针对此问题做些什么。

1 个答案:

答案 0 :(得分:0)

这是一个老问题,但我最近在复制粘贴OP使用的相同代码后遇到了同样的问题。

您正在方法createImageFile()中启动ACTION_IMAGE_CAPTURE意图之前为照片创建文件。您需要处理未正确拍摄照片的情况并处理您创建的文件。例如:

    if(requestCode == 1) {
        if(resultCode == RESULT_OK) {
            //pic taken properly
        } else {
            //pic was not taken properly, deal with the empty file you created
        }
    }