通过相机获取最近拍摄的图片路径和文件名。

3

我需要将拍摄的图片上传到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服务器。


如果您习惯将相机拍摄的图像存储在自己的文件夹中,我可能有一个解决方案供您参考。 - Siddharth Lele
任何解决方案对我来说都是受欢迎的。我只想要捕获图像的完整路径和图像名称。 - Umesh
你是如何解决这个问题的? - kml_ckr
@kamil 我已经在下面发布了解决方案。它对我有效。 - Umesh
@Umesh 很好的问题,对我有所帮助。谢谢 :) - android_dev
4个回答

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

0

在创建路径时,您只是保存“标题”。 您没有提供实际的路径和文件名,让相机使用进行存储。 由于这个原因,相机将文件存储在其默认位置,带有您提供的“标题”。

在您的代码中,您做得很好,但请按照以下步骤执行以获得相同的文件名:

不要使用:

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

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

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

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


0

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

我参考了这个链接:这里

只需要将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>

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

愉快编码。


我使用这段代码,但相机预览显示在错误的相机预览上。你有解决办法吗? - kml_ckr
我在 preview.addView(mCameraPreview) 处遇到了空指针异常,请帮忙解决一下? - user2125722

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接