【问题标题】:Get path and imagename of recently captured image through camera通过相机获取最近捕获的图像的路径和图像名称
【发布时间】:2012-10-29 11:59:37
【问题描述】:

我必须将捕获的图像上传到 ftp 服务器。我正在通过相机捕获图像,我想获取该图像的图像名称和路径。我正在使用以下代码获取图像路径:

int ACTION_TAKE_PICTURE = 1;
String selectedImagePath;
Uri mCapturedImageURI;

Button loadButton;
ImageView img;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new_ftpsdemo);
     img = (ImageView)findViewById(R.id.image);

    ContentValues values = new ContentValues();
    values.put(MediaStore.Images.Media.TITLE, "yahoo.jpg");
    mCapturedImageURI  = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intentPicture.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
    startActivityForResult(intentPicture,ACTION_TAKE_PICTURE);

}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode == ACTION_TAKE_PICTURE){
        selectedImagePath = getRealPathFromURI(mCapturedImageURI);
        Log.v("selectedImagePath", selectedImagePath);
        img.setImageBitmap( BitmapFactory.decodeFile(selectedImagePath));
    }
}


public String getRealPathFromURI(Uri contentUri)
    {
        try
        {
            String[] proj = {MediaStore.Images.Media.DATA};
            Cursor cursor = managedQuery(contentUri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }
        catch (Exception e)
        {
            return contentUri.getPath();
        }
    }

但我得到这样的图像路径:

/mnt/sdcard/DCIM/Camera/1352443194885.jpg

因为我正在保存名称“yahoo.jpg”。 我知道这可能是一个非常简单的问题,但我无法获得相同的图像名和路径。 所以我无法将图像上传到 ftp 服务器。

【问题讨论】:

  • 如果您愿意将相机中的图像存储在自己的文件夹中,我可能会为您提供解决方案。
  • 我随时欢迎任何解决方案.. 只是我想要捕获图像的完整路径和图像名称。
  • 你是怎么解决这个问题的?
  • @kamil 我已经在下面发布了解决方案。它对我有用。
  • @Umesh 好问题,它对我有帮助谢谢:)

标签: android image ftp camera


【解决方案1】:

检查这个...把它放在你的 onActivityResult 中

           Uri selectedImage = intent.getData();

           String[] filePathColumn = {MediaStore.Images.Media.DATA};
           Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
           cursor.moveToFirst();
           int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
           String filePath = cursor.getString(columnIndex);
           Log.v("log","filePath is : "+filePath); 

【讨论】:

    【解决方案2】:

    创建路径时,您只是保存“标题”。您没有给出相机应该用来存储的实际路径和文件名。由于此相机将文件存储在您提供的“标题”的默认位置。

    您在代码中一切正常,但只需执行以下操作以获得相同的文件名:

    相对于:

    ContentValues values = new ContentValues();
    values.put(MediaStore.Images.Media.TITLE, "yahoo.jpg");
    mCapturedImageURI  =  getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    

    使用这个:

        StringBuilder path = new StringBuilder();
        path.append(Environment.getExternalStorageDirectory());
        path.append(// any location say "/Pictures/" //); // Do check if the folder is present. Else create one.
        path.append("yahoo");
            path.append(".jpg");
        File file = new File(path.toString());
        mCapturedImageURI = Uri.fromFile(file);
    

    【讨论】:

      【解决方案3】:

      使用它来启动相机的 Intent:

      哦。 Uri targetURI 是一个全局声明。

      Intent getCameraImage = new Intent("android.media.action.IMAGE_CAPTURE");
      
      File cameraFolder;
      
      if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
          cameraFolder = new File(android.os.Environment.getExternalStorageDirectory(),"your_app_name/camera");
      else
          cameraFolder= StatusUpdate.this.getCacheDir();
      if(!cameraFolder.exists())
          cameraFolder.mkdirs();
      
      File photo = new File(Environment.getExternalStorageDirectory(), "your_app_name/camera/camera_snap.jpg");
      getCameraImage.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
      targetURI = Uri.fromFile(photo);
      
      startActivityForResult(getCameraImage, 1);
      

      而在onActivityResult()

      getContentResolver().notifyChange(targetURI, null);
      
      ContentResolver cr = getContentResolver();
      
      try {       
          // SET THE IMAGE FROM THE CAMERA TO THE IMAGEVIEW
          bmpImageCamera = android.provider.MediaStore.Images.Media.getBitmap(cr, targetURI);
      
          // SET THE IMAGE FROM THE GALLERY TO THE IMAGEVIEW
          imgvwSelectedImage.setImageBitmap(bmpImageCamera);
      
      } catch (Exception e) {
          e.printStackTrace();
      }
      

      这段代码使用您选择的名称创建一个文件夹。您可以在此处更改文件夹名称:new File(android.os.Environment.getExternalStorageDirectory(),"your_app_name/camera");

      此外,每次调用 Intent 以获取相机图像时,这都会覆盖 camera_snap.jpg

      此代码不考虑内存不足异常,而只是演示如何将相机图像返回到您的应用程序。

      编辑:差点忘了。如果您还没有这样做,您需要将此权限添加到您的Manifest.xml<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

      【讨论】:

        【解决方案4】:

        我已经用下面的代码解决了这个问题。它对我有用。

        我已经参考了这个链接:here

        只需要将文件路径和 imageName 设为全局变量

        MyCameraActivity.java

        public class MyCameraActivity extends Activity {
        private Camera mCamera;
        private CameraPreview mCameraPreview;
        public static String imageFilePath;
        public static String imageName;
        
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            mCamera = getCameraInstance();
            mCameraPreview = new CameraPreview(this, mCamera);
            FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
            preview.addView(mCameraPreview);
        
            Button captureButton = (Button) findViewById(R.id.button_capture);
            captureButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mCamera.takePicture(null, null, mPicture);
                }
            });
        }
        
        /**
         * Helper method to access the camera returns null if it cannot get the
         * camera or does not exist
         * 
         * @return
         */
        private Camera getCameraInstance() {
            Camera camera = null;
            try {
                camera = Camera.open();
            } catch (Exception e) {
                // cannot get camera or does not exist
            }
            return camera;
        }
        
        PictureCallback mPicture = new PictureCallback() {
            @Override
            public void onPictureTaken(byte[] data, Camera camera) {
                File pictureFile = getOutputMediaFile();
                if (pictureFile == null) {
                    return;
                }
                try {
                    FileOutputStream fos = new FileOutputStream(pictureFile);
                    fos.write(data);
                    fos.close();
                } catch (FileNotFoundException e) {
        
                } catch (IOException e) {
                }
            }
        };
        
        private static File getOutputMediaFile() {
            File filePath = new File(
                    Environment
                            .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                    "MyCameraApp");
        
            if (!mediaStorageDir.exists()) {
                if (!mediaStorageDir.mkdirs()) {
                    Log.d("MyCameraApp", "failed to create directory");
                    return null;
                }
            }
            // Create a media file name
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                    .format(new Date());
        imageName = timeStamp +".jpg"; // name of captured image
            File mediaFile;
            mediaFile = new File(mediaStorageDir.getPath() + File.separator
                    + imageName);
            imageFilePath = mediaFile.toString(); // you can get path of image saved
            return mediaFile;
        }
        

        }

        CameraPreview.java:

        public class CameraPreview extends SurfaceView implements
            SurfaceHolder.Callback {
        private SurfaceHolder mSurfaceHolder;
        private Camera mCamera;
        
        // Constructor that obtains context and camera
        @SuppressWarnings("deprecation")
        public CameraPreview(Context context, Camera camera) {
            super(context);
            this.mCamera = camera;
            this.mSurfaceHolder = this.getHolder();
            this.mSurfaceHolder.addCallback(this);
            this.mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
        
        @Override
        public void surfaceCreated(SurfaceHolder surfaceHolder) {
            try {
                mCamera.setPreviewDisplay(surfaceHolder);
                mCamera.startPreview();
            } catch (IOException e) {
                // left blank for now
            }
        }
        
        @Override
        public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
            mCamera.stopPreview();
            mCamera.release();
        }
        
        @Override
        public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
                int width, int height) {
            // start preview with new settings
            try {
                mCamera.setPreviewDisplay(surfaceHolder);
                mCamera.startPreview();
            } catch (Exception e) {
                // intentionally left blank for a test
            }
        }
        

        }

        main.xml:

        <?xml version="1.0" encoding="utf-8"?>
        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="horizontal" >
        <FrameLayout
            android:id="@+id/camera_preview"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1" />
        <Button
            android:id="@+id/button_capture"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="Capture" />
        </LinearLayout>
        

        androidmanifyt.xml 中需要以下权限:

        <uses-feature android:name="android.hardware.camera" />
        <uses-permission android:name="android.permission.CAMERA" />
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
        

        现在我可以获取最近捕获的图像的 imageName 和 imagepath 并轻松将此图像上传到 ftp 服务器。

        编码愉快。

        【讨论】:

        • 我使用此代码,但相机预览在 camerapreview 上显示错误。你有解决方案吗?
        • 我在 preview.addView(mCameraPreview); 处得到一个空指针异常;请帮忙?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多