2015-12-12 127 views
1

我一直在這個問題上停留了一段時間。 我正嘗試用相機拍照並將全尺寸圖片直接保存到內存中。 我可以保存到外部存儲沒有一個小故障,但由於某種原因,我無法得到它的內部記憶工作。 下面的解決方案只保存數據對象返回的小圖片,而不是全尺寸圖片。 似乎相機不檢索全尺寸圖片,或者當我使用文件功能(新File,FileOutputStream ...)時,Android不會從相機Intent(顯示空白圖像)中檢索圖像。Android - 從相機拍攝照片並將其保存到內部存儲

我閱讀所有的論壇,教程和嘗試不同的方式來實現這一目標,但我還沒有找到答案。我不能是唯一一個試圖做到這一點的人。 你能幫我解決這個問題嗎? 謝謝!

這裏是我的代碼:

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; 
    }  
} 
+0

您是否知道內部存儲意味着這一點 - 「默認情況下,保存到內部存儲的文件對您的應用程序來說是私有的,其他應用程序無法訪問它們(用戶也無法訪問它們)。」http://developer.android.com /intl/ru/guide/topics/data/data-storage.html#files內部 –

+0

感謝您的回答。是的,我意識到這一點,但這對我有什麼幫助?我試圖將內容保存在內部存儲器中,並將其顯示在我的應用程序中。 –

回答

-2

我找到了解決辦法!我沒有使用原生的相機應用程序,而是創建了我自己的相機類,並使用相機通過回調發回的數據。工作順利!

+1

爲你的答案和你的問題添加一些代碼,沒有它的話,它容易遭受downvotes。 – cafebabe1991

相關問題