首页 文章

Android - 从相机拍摄照片并将其保存到内部存储

提问于
浏览
1

我一直坚持这个问题一段时间了 . 我正在尝试用相机拍照并将 full size picture 直接保存到内部存储器中 . 我可以在没有故障的情况下保存到外部存储器,但由于某种原因,我不能让它为内部存储器工作 . 下面的解决方案仅保存数据对象返回的小图片,而不是全尺寸图片 . 似乎相机没有检索全尺寸图片,或者当我使用文件功能(新文件,FileOutputStream ...)时,Android没有从相机Intent检索图像(显示空白图像) .

我阅读了所有论坛,教程并尝试了不同的方法来实现这一目标,但我还没有找到答案 . 我不可能是唯一一个试图这样做的人 . 你能帮帮我解决这个问题吗?谢谢!

这是我的代码:

public class AddItem extends Fragment {
    ListCell cell = new ListCell();
    View view;
    private Bitmap mImageBitmap;
    protected myCamera cameraObject = null;
    private Button saveBtn;
    private Button cancelBtn;
    DBSchema dbSchema;
    protected boolean bdisplaymessage;
    protected boolean ExternalStorage = false;

    public AddItem(){

    }

    private class ListCell{
        private EditText total;
        private ImageView mImageView;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View rootView = inflater.inflate(R.layout.add_item, container,
                false);

        saveBtn = (Button) rootView.findViewById(R.id.SaveItem);
        cancelBtn = (Button) rootView.findViewById(R.id.CancelItem);

        cameraObject = new myCamera();

        cell.total = (EditText) rootView.findViewById(R.id.item_total_Value);
        cell.mImageView = (ImageView) rootView.findViewById(R.id.item_logo);
        cell.mImageView.setImageResource(R.drawable.camera_icon);

        cell.mImageView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                    dispatchTakePictureIntent();
            }
        });

        saveBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                //save item to internal db
                //get names of columns from db
                bdisplaymessage = true;
                dbSchema = new DBSchema();
                Transaction transac = dbSchema.new Transaction();
                Context context = getActivity().getApplicationContext();

                //put values in content values
                ContentValues values = new ContentValues();
                values.put(transac.Total,cell.total.getText().toString());

                StatusData statusData = ((MyFunctions) getActivity().getApplication()).statusData;
                long nInsert = 0;
                nInsert = statusData.insert(values,dbSchema.table_transaction);

                if(nInsert!=0){
                    Toast.makeText(context, "inserted " + nInsert , Toast.LENGTH_LONG).show();
                }
                else{
                    Toast.makeText(context, "not inserted " + nInsert , Toast.LENGTH_LONG).show();
                }

            }
        });

        cancelBtn.setOnClickListener(new OnClickListener() {

            @Override
                public void onClick(View v) {
                    //redirect to home page 
    getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new LoadMenu()).commit();
                }
            });

    return rootView;
}

    // Some lifecycle callbacks so that the image can survive orientation change
    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putParcelable(cameraObject.BITMAP_STORAGE_KEY, mImageBitmap);
        outState.putBoolean(cameraObject.IMAGEVIEW_VISIBILITY_STORAGE_KEY, (mImageBitmap != null) );
        super.onSaveInstanceState(outState);
    }

    //take picture
    private void dispatchTakePictureIntent() {

        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //takePictureIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            String mCurrentPhotoPath;

            File f = null;

            try {
                //create image
                f = cameraObject.setUpPhotoFile(getResources().getString(R.string.album_name),ExternalStorage, getActivity().getApplicationContext());

                cameraObject.setCurrentPath(f.getAbsolutePath());
                Log.d("uri_fromfile",Uri.fromFile(f).toString());

                //uncomment the line below when ExternalStorage=true
                //takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
            } catch (IOException e) {
                e.printStackTrace();
                f = null;
                mCurrentPhotoPath = null;
            }

            startActivityForResult(takePictureIntent, cameraObject.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
    }

    @Override
    public void onActivityResult(int requestcode, int resultCode, Intent data) {

        if (requestcode == cameraObject.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == getActivity().RESULT_OK) {
            handleCameraPhoto(data);
        }

    }


    private void handleCameraPhoto(Intent data) {
        setPic(data);
        galleryAddPic();
    }

    private void setPic(Intent data) {

        /* There isn't enough memory to open up more than a couple camera photos */
        /* So pre-scale the target bitmap into which the file is decoded */

        /* Get the size of the ImageView */
        int targetW = cell.mImageView.getWidth();
        int targetH = cell.mImageView.getHeight();

        /* Get the size of the image */
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inJustDecodeBounds = true;


        BitmapFactory.decodeFile(cameraObject.getCurrentPath(), bmOptions);
        Log.d("image_path",cameraObject.getCurrentPath());

        int photoW = bmOptions.outWidth;
        int photoH = bmOptions.outHeight;

        /* Figure out which way needs to be reduced less */
        int scaleFactor = 1;
        if ((targetW > 0) || (targetH > 0)) {
            scaleFactor = Math.min(photoW/targetW, photoH/targetH); 
        }

        /* Set bitmap options to scale the image decode target */
        bmOptions.inJustDecodeBounds = false;
        bmOptions.inSampleSize = scaleFactor;
        bmOptions.inPurgeable = true;

        /* Decode the JPEG file into a Bitmap */
        Bitmap bitmap = null;
        if(ExternalStorage){
             bitmap = BitmapFactory.decodeFile(cameraObject.getCurrentPath(), bmOptions);
        }

        else{
                File internalStorage = getActivity().getApplicationContext().getDir("imageDir", Context.MODE_PRIVATE);
                File reportFilePath = new File(internalStorage, cameraObject.JPEG_FILE_PREFIX +"hello" + ".jpg");
                String picturePath = reportFilePath.toString();

                FileOutputStream fos = null;
               try {
                  fos = new FileOutputStream(reportFilePath);
                  bitmap = (Bitmap) data.getExtras().get("data");
                  bitmap.compress(Bitmap.CompressFormat.PNG, 100 /*quality*/, fos);
                  fos.close();

                  }
               catch (Exception ex) {
                  Log.i("DATABASE", "Problem updating picture", ex);
                  picturePath = "";
                  }




/* below is a bunch of options that I tried with decodefile, FileOutputStream... none seems to work */
            //File out = new File(getActivity().getApplicationContext().getFilesDir(),cameraObject.JPEG_FILE_PREFIX + "hello");
            //bitmap = BitmapFactory.decodeFile(out.getAbsolutePath());

               //FileOutputStream fos = null;
               //try {
                   //fos = new FileOutputStream(new File(getActivity().getApplicationContext().getFilesDir(),"/" + cameraObject.JPEG_FILE_PREFIX + "hello" + cameraObject.JPEG_FILE_SUFFIX).getAbsolutePath());
                   //bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
              // Use the compress method on the BitMap object to write image to the OutputStream
                   //fos.close();
                   //Bitmap bitmap = null;
                   /*try{
                       FileInputStream fis = new FileInputStream(new File(getActivity().getApplicationContext().getFilesDir(),"/" + cameraObject.JPEG_FILE_PREFIX + "hello" + cameraObject.JPEG_FILE_SUFFIX).getAbsolutePath());
                               //getActivity().getApplicationContext().openFileInput(cameraObject.getCurrentPath());
                        bitmap = BitmapFactory.decodeStream(fis);
                        //
                        fis.close();
                    }
                    catch(Exception e){
                        Log.d("what?",e.getMessage());
                        bitmap = null;
                    }*/


               /*} catch (Exception e) {
                   e.printStackTrace();
               }*/

            /*File mypath=new File(getActivity().getApplicationContext().getFilesDir(),"/" + cameraObject.JPEG_FILE_PREFIX + "hello" + cameraObject.JPEG_FILE_SUFFIX);
            bitmap = BitmapFactory.decodeFile(mypath.getAbsolutePath());*/
            //bitmap = (Bitmap) data.getExtras().get("data");

        }
        /* Associate the Bitmap to the ImageView */
        cell.mImageView.setImageBitmap(bitmap);
        cell.mImageView.setVisibility(View.VISIBLE);
    }

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

}

我的另一个名为myCamera的类处理相机:

public class myCamera extends MainMenu{

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

    public static final int MEDIA_TYPE_IMAGE = 1;
    public static final int MEDIA_TYPE_VIDEO = 2;

    protected static final int ACTION_TAKE_PHOTO_B = 1;
    protected static final int ACTION_TAKE_PHOTO_S = 2;

    protected int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = MEDIA_TYPE_IMAGE;
    protected Uri fileUri;

    protected String mCurrentPhotoPath;

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

    private static final String CAMERA_DIR = "/dcim/";
    protected String mAlbumName;
    protected AlbumStorageDirFactory mAlbumStorageDirFactory = null;

    protected String getAlbumName() {
        return "test";
    }

    protected String getCurrentPath(){
        return mCurrentPhotoPath;
    }

    protected void setCurrentPath(String mCurrentPhotoPath){
        this.mCurrentPhotoPath=mCurrentPhotoPath;
    }

    public File getAlbumStorageDir(String albumName) {
        return new File (
                Environment.getExternalStorageDirectory()
                + CAMERA_DIR
                + albumName
        );
    }

    private File getAlbumDir() {
        File storageDir = null;

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

        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {

            storageDir = getAlbumStorageDir(getAlbumName());

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

        } else {
            Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
        }

        return storageDir;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub

        super.onCreate(savedInstanceState);
        setContentView(R.layout.base_for_drawer);

        mAlbumName = getIntent().getStringExtra("AlbumName");

    }

    public myCamera(){
    }

    //save full size picture
    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 storageDir = getAlbumDir();
        File image = File.createTempFile(imageFileName,JPEG_FILE_SUFFIX, storageDir);
        return image;
    }

    protected File setUpPhotoFile(String albumName, boolean ExternalStorage, Context context) throws IOException {

        mAlbumName = albumName;
        File f =null;

        if(ExternalStorage){
            f = createImageFile();
        }
        else{
            f = saveToInternalSorage(context);
        }
        // Save a file: path for use with ACTION_VIEW intents
        if(f !=null){
            mCurrentPhotoPath = f.getAbsolutePath();
        }
        return f;
    }

    private File saveToInternalSorage(Context context) throws IOException{
        ContextWrapper cw = new ContextWrapper(context);


        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = JPEG_FILE_PREFIX + "hello";
        // path to /data/data/yourapp/app_data/imageDir
        File directory = context.getDir("imageDir", Context.MODE_PRIVATE);
        File mypath=new File(directory,imageFileName + JPEG_FILE_SUFFIX);


        /*below is a bunch of options that I tried*/
        //File directory =context.getFilesDir();
        //File directory = new File(getFilesDir(),imageFileName,Context.MODE_PRIVATE);

        // Create imageDir
        //File image = File.createTempFile(imageFileName,JPEG_FILE_SUFFIX, storageDir);
        //File mypath = File.createTempFile(imageFileName,JPEG_FILE_SUFFIX, directory);
        //return image;
        return mypath;
    }       
}

1 回答

  • -2

    我找到了解决方案!我没有使用原生相机应用程序,而是创建了我自己的相机类,并使用相机通过回调发回的数据 . 工作顺利!

相关问题