通过相机获取最近捕获的图像的路径和图像名称

时间:2012-11-09 06:50:52

标签: android image ftp camera

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

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

但我得到像这样的imagepath:

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

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

4 个答案:

答案 0 :(得分: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); 

答案 1 :(得分:0)

创建路径时,您只需保存"标题"。您没有提供相机应该用来存储的实际路径和文件名。因此,Camera将文件存储在默认位置,使用" Title"你提供了。

您在代码中做得很好,但只需执行以下操作即可使用相同的文件名:

Intead of:

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

答案 2 :(得分:0)

使用此选项启动相机的意图:

喔。 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

此代码不考虑Out of Memory异常,但仅仅是演示如何将相机图像恢复到您的应用程序。

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

答案 3 :(得分:0)

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

我已经提到过这个链接:here

只需要创建filepath和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>

androidmanifiest.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服务器。

快乐的编码。