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

时间:2015-12-12 23:02:45

标签: android android-intent android-camera internal-storage

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

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

这是我的代码:

    String input = "1994-09-09";
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    Date date = df.parse(input);
    System.out.println( date);
    java.sql.Date sqlDate = new java.sql.Date( date.getTime() );
    System.out.println( sqlDate);

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

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);
}

}

1 个答案:

答案 0 :(得分:-2)

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

相关问题