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

4

4 回答 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); 
于 2012-11-09T09:24:07.383 回答
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);
于 2012-11-09T09:00:38.937 回答
0

使用它来启动相机的 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();
}

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

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

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

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

于 2012-11-09T09:05:56.243 回答
0

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

我已经提到了这个链接:这里

只需要制作文件路径和图像名称全局变量

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

}

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

快乐编码。

于 2012-11-09T13:53:34.347 回答