Android 如何获取拍摄的图像并将其提交到服务器

Android 如何获取拍摄的图像并将其提交到服务器,android,android-camera,android-file,Android,Android Camera,Android File,目前,我可以将SD卡中的现有图像上载到我的服务器。我是Android编程领域的新手,我想知道如何动态地抓取新拍摄的图像并将其提交到服务器 这就是我到目前为止为onClick活动准备的内容 public void onClick(View arg0) { // TODO Auto-generated method stub camera.takePicture(myShutterCallback,

目前,我可以将SD卡中的现有图像上载到我的服务器。我是Android编程领域的新手,我想知道如何动态地抓取新拍摄的图像并将其提交到服务器

这就是我到目前为止为onClick活动准备的内容

        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            camera.takePicture(myShutterCallback, 
                    myPictureCallback_RAW, myPictureCallback_JPG);

            new Thread(new Runnable() {
                public void run() {

                    File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "nypdImages");
                    //hard code
                    String path = mediaStorageDir.getPath() + "/" + "IMG_20000106_124322.jpg";

                    int response= uploadFile(path);
                    System.out.println("RES : " + response);                        
                }
              }).start();   

        }});
这是我相机功能的代码

    ShutterCallback myShutterCallback = new ShutterCallback(){

    @Override
    public void onShutter() {
        // TODO Auto-generated method stub

    }};

PictureCallback myPictureCallback_RAW = new PictureCallback(){

    @Override
    public void onPictureTaken(byte[] arg0, Camera arg1) {
        // TODO Auto-generated method stub

    }};

PictureCallback myPictureCallback_JPG = new PictureCallback(){

    @Override
    public void onPictureTaken(byte[] arg0, Camera arg1) {
        // TODO Auto-generated method stub

        FileOutputStream outStream = null;

        try 
        {
            File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "nypdImages");

            if (!mediaStorageDir.exists()) 
            {
                if (!mediaStorageDir.mkdirs()) 
                {
                    Log.d("nypdImages", "Oops! Failed create " + "nypdImages" + " directory");
                }
            }

            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
            String path = mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg";


            outStream = new FileOutputStream(String.format(path, System.currentTimeMillis()));
            outStream.write(arg0);
            outStream.close();

            sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory()))); 
        } 
        catch (FileNotFoundException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        catch (IOException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally 
        {
            Toast.makeText(getApplicationContext(), "Image Saved", Toast.LENGTH_SHORT).show();
            //VuzixCamera.super.onBackPressed();
        }

        camera.startPreview();
    }};

有两个类upload和main_activity。我在这里把它放在xml文件中

public class MainActivity extends Activity {

    final static int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1;
    private static final String TAG = "CaptureImage.java";
    public static ImageView showImg = null;
    static String uploadFilePath = " ";
    static String Path;
    static int delete_image_id = 0;
    static TextView imageDetails = null;
    // FeedReaderDbHelper mDbHelper = new FeedReaderDbHelper(CaptureImage.this);
    static Cursor cursor = null;
    public ProgressDialog dialog_upload = null;
    public String s_name;
    public String s_Adress;
    int serverResponseCode = 0;
    TextView shift_display;
    Uri imageUri = null;
    OnClickListener oclBtnOk = new OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.i("VALUES", "It is Working");
            String fileName = "Camera_Example.jpg";
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.TITLE, fileName);
            values.put(MediaStore.Images.Media.DESCRIPTION,
                "Image capture by camera");

            imageUri = getContentResolver().insert(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);

            startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);

            /*************************** Camera Intent End ************************/

        }
    };
    MainActivity CameraActivity = null;
    Upload upload;
    Button outlet_names_show;
    double latitude;
    double longitude;
    OnClickListener oclBtnOk3 = new OnClickListener() {
        @Override
        public void onClick(View v) {

            if (showImg.getDrawable() == null) {
                Toast.makeText(MainActivity.this, " Picture was not captured ",
                    Toast.LENGTH_SHORT).show();
            } else {
                upload_prescription();
                // CallSummery.flag_bt_merchan=true;

            }

        }
    };
    private Button buttonback;

    /**
     * ********* Convert Image Uri path to physical path *************
     */

    public static String convertImageUriToFile(Uri imageUri, Activity activity) {

        int imageID = 0;

        try {

            /*********** Which columns values want to get *******/
            String[] proj = {MediaStore.Images.Media.DATA,
                MediaStore.Images.Media._ID,
                MediaStore.Images.Thumbnails._ID,
                MediaStore.Images.ImageColumns.ORIENTATION};

            cursor = activity.getContentResolver().query(imageUri, proj, null,
                null, null);

            // Get Query Data

            int columnIndex = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media._ID);
            int file_ColumnIndex = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

            // int orientation_ColumnIndex = cursor.
            // getColumnIndexOrThrow(MediaStore.Images.ImageColumns.ORIENTATION);

            int size = cursor.getCount();

            /******* If size is 0, there are no images on the SD Card. *****/

            if (size == 0) {

                // imageDetails.setText("No Image");
            } else {

                if (cursor.moveToFirst()) {

                    imageID = cursor.getInt(columnIndex);
                    delete_image_id = imageID;

                    Path = cursor.getString(file_ColumnIndex);

                }

            }

        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        // Return Captured Image ImageID ( By this ImageID Image will load from
        // sdcard )

        return "" + imageID;
    }

    protected void onCreate(Bundle savedInstanceState) {
        MainActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        CameraActivity = this;
        showImg = (ImageView) findViewById(R.id.showImg);
        upload = new Upload(MainActivity.this);
        final Button photo = (Button) findViewById(R.id.photo);
        final Button upload = (Button) findViewById(R.id.upload);


        photo.setOnClickListener(oclBtnOk);
        upload.setOnClickListener(oclBtnOk3);



    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (imageUri != null) {
            outState.putString("cameraImageUri", imageUri.toString());
        }
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (savedInstanceState.containsKey("cameraImageUri")) {
            imageUri = Uri
                .parse(savedInstanceState.getString("cameraImageUri"));
        }
    }

    public void upload_prescription() {
        dialog_upload = ProgressDialog.show(MainActivity.this, "",
            "Uploading file...", true);




        new Thread(new Runnable() {
            public void run() {
                runOnUiThread(new Runnable() {
                    public void run() {

                    }
                });

                createDirectoryIfNeeded();




                upload.uploadFile(uploadFilePath);

            }
        }).start();

    }







    private void createDirectoryIfNeeded() {
        File direct = new File(Environment.getExternalStorageDirectory()
            + "/Capturetemp");

        if (!direct.exists()) {
            if (direct.mkdir()) {
                // directory is created;
            }

        }

    }


    public void copy(String lo, String lan) throws JSONException {

        String sdCard = Environment.getExternalStorageDirectory().toString();

        Random ran = new Random();

        uploadFilePath = sdCard + "/Capturetemp/" + ran.toString() + ".jpg";

        File sourceLocation = new File(Path);
        File targetLocation = new File(uploadFilePath);
        Log.v(TAG, "sourceLocation: " + sourceLocation);
        Log.v(TAG, "targetLocation: " + targetLocation);

        try {

            // 1 = move the file, 2 = copy the file
            int actionChoice = 2;

            // moving the file to another directory
            if (actionChoice == 1) {

                if (sourceLocation.renameTo(targetLocation)) {
                    Log.v(TAG, "Move file successful.");
                } else {
                    Log.v(TAG, "Move file failed.");
                }

            }

            // we will copy the file
            else {

                // make sure the target file exists

                if (sourceLocation.exists()) {

                    InputStream in = new FileInputStream(sourceLocation);
                    OutputStream out = new FileOutputStream(targetLocation);

                    // Copy the bits from instream to outstream
                    byte[] buf = new byte[1024];
                    int len;

                    while ((len = in.read(buf)) > 0) {
                        out.write(buf, 0, len);
                    }

                    in.close();
                    out.close();

                    Log.v(TAG, "Copy file successful.");

                } else {
                    Log.v(TAG, "Copy file failed. Source file missing.");
                }

            }

        } catch (NullPointerException e) {
            // e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {

            if (resultCode == RESULT_OK) {

                /*********** Load Captured Image And Data Start ***************/

                String imageId = convertImageUriToFile(imageUri, CameraActivity);

                // Create and excecute AsyncTask to load capture image

                new LoadImagesFromSDCard(MainActivity.this).execute(""
                    + imageId);

                /*********** Load Captured Image And Data End ****************/

            } else if (resultCode == RESULT_CANCELED) {

                Toast.makeText(this, " Picture was not taken ",
                    Toast.LENGTH_SHORT).show();

            } else {

                Toast.makeText(this, " Picture was not taken ",
                    Toast.LENGTH_SHORT).show();

            }
        }

    }

    @Override
    public void onBackPressed() {

    }

    public class LoadImagesFromSDCard extends AsyncTask<String, Void, Void> {

        Context context;
        Bitmap mBitmap;
        private ProgressDialog loadingdailog;

        public LoadImagesFromSDCard(MainActivity context) {
            this.context = context;

        }

        @Override
        protected void onPreExecute() {
            loadingdailog = new ProgressDialog(context);
            loadingdailog.setMessage("Loading Image.....");
            loadingdailog.show();

        }

        // Call after onPreExecute method
        @Override
        protected Void doInBackground(String... urls) {

            Bitmap bitmap = null;
            Bitmap newBitmap = null;
            Uri uri = null;

            try {

                uri = Uri.withAppendedPath(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, ""
                        + urls[0]);

                /************** Decode an input stream into a bitmap. *********/
                bitmap = BitmapFactory.decodeStream(getContentResolver()
                    .openInputStream(uri));

                if (bitmap != null) {

                    /********* Creates a new bitmap, scaled from an existing bitmap. ***********/

                    newBitmap = Bitmap.createScaledBitmap(bitmap, 350, 350,
                        true);
                    // SaveIamge(newBitmap);
                    bitmap.recycle();
                    if (newBitmap != null) {

                        mBitmap = newBitmap;
                    }
                }
            } catch (IOException e) {
                // Error fetching image, try to recover

                /********* Cancel execution of this task. **********/
                cancel(true);
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void unused) {

            if (loadingdailog.isShowing() && loadingdailog != null) {

                loadingdailog.dismiss();
                loadingdailog = null;
            }

            if (mBitmap != null) {
                showImg.setImageBitmap(mBitmap);

            }
        }
    }


}
xml文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFFF"
    android:orientation="vertical"
    android:padding="10dp"
    android:weightSum="1" >

    <ImageView
        android:id="@+id/showImg"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:contentDescription="bla bla" />



    <Button
        android:id="@+id/photo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"

        android:text="Capture Image"
        android:textSize="26sp" />

    <Button
        android:id="@+id/upload"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"

        android:text="Upload Photo"
        android:textSize="26sp" />

</LinearLayout>


对于图像uri,您应该粘贴您的文件上载路径

希望此答案对您有所帮助

拍摄新图片代码:

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

public class CameraUtil  extends Activity {

    private final static int REQUEST_TAKE_PHOTO=200;
    private final String TAG = "Camera";

    String mCurrentPhotoPath;
    String path;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if(! isDeviceSupportCamera()){
            Log.e(TAG,"Camera Not Supported");
            Intent returnFromCameraIntent = new Intent();
            setResult(RESULT_CANCELED,returnFromCameraIntent);     
            finish();
        }
        else{
            dispatchTakePictureIntent();
        }

    }

     private void dispatchTakePictureIntent() {
        Log.i(TAG,"Dispatch Take Picture Intent");

        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent       
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go      
                File photoFile = null;
                try{
                    photoFile = createImageFile();
                }catch (IOException ex) {
                    // Error occurred while creating the File
                    ex.printStackTrace();
                    Log.i(TAG,"Error occurred while creating the File");
                }
                // Continue only if the File was successfully created
                if (photoFile != null) {
                    //  fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);  
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                    startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
                }       
        }
     }


        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            Log.i(TAG,"On Activity Result");
            File file= new File(path);  

            if (requestCode == REQUEST_TAKE_PHOTO  && resultCode == RESULT_OK && path!=null && file.length()>0) {
                        Intent returnFromCameraIntent = new Intent();
                        returnFromCameraIntent.putExtra("picturePath",path);
                        setResult(RESULT_OK,returnFromCameraIntent);  
                        finish();
                        Log.i(TAG,"Camera Closed");
                }else{
                    Log.i(TAG,"On Result CANCEL");
                    // cancelled Image capture
                    try{
                    /*delete Temperory created file*/  
                        file.delete();
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                    Intent returnFromCameraIntent = new Intent();
                    setResult(RESULT_CANCELED,returnFromCameraIntent);     
                    finish();
                    Log.i(TAG,"Image Capture Cancelled");
           }
           galleryAddPic();
     }

     private File createImageFile() throws IOException {
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",Locale.getDefault()).format(new Date());
            String imageFileName = "CAMERA_" + timeStamp + "_WA0001";

            File root = new File(Environment.getExternalStorageDirectory()
                     + File.separator + "MyApp"+ File.separator);

            if(!root.exists()){
                    root.mkdirs();  
            }

           // File storageDir = Environment.getExternalStoragePublicDirectory(
           //         Environment.DIRECTORY_PICTURES);
            File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                root      /* directory */
            );
            // Save a file: path for use with ACTION_VIEW intents
            mCurrentPhotoPath = "file:" + image.getAbsolutePath();
            path=""+image.getAbsolutePath();
            return image;
    }

     private void galleryAddPic() {
            Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            File f = new File(mCurrentPhotoPath);
            Uri contentUri = Uri.fromFile(f);
            mediaScanIntent.setData(contentUri);
            this.sendBroadcast(mediaScanIntent);
     }

     private boolean isDeviceSupportCamera() {
            if (getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
                // this device has a camera
                return true;
            } else {
                // no camera on this device
                return false;
            }
     }
}
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;

public class GalleryUtil extends Activity{
    private final static int RESULT_LOAD_GALLERY=100;
    public static final int MEDIA_TYPE_IMAGE = 1;
    private static final String TAG = "Gallery_Image";

    String mCurrentPhotoPath;
    File photoFile = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try{
            Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(i, RESULT_LOAD_GALLERY); 
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
         super.onActivityResult(requestCode, resultCode, data);
         Log.i(TAG,"On Activity Result");        
         if (requestCode == RESULT_LOAD_GALLERY && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.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 picturePath = cursor.getString(columnIndex);
            cursor.close();

                Intent returnFromGalleryIntent = new Intent();
                returnFromGalleryIntent.putExtra("picturePath",picturePath);
                setResult(RESULT_OK,returnFromGalleryIntent);     
                finish();

           }else{
                Log.i(TAG,"Image Capture Cancelled");
                Intent returnFromGalleryIntent = new Intent();
                setResult(RESULT_CANCELED,returnFromGalleryIntent);     
                finish();
           }
    }
}
选择现有图片代码:

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

public class CameraUtil  extends Activity {

    private final static int REQUEST_TAKE_PHOTO=200;
    private final String TAG = "Camera";

    String mCurrentPhotoPath;
    String path;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if(! isDeviceSupportCamera()){
            Log.e(TAG,"Camera Not Supported");
            Intent returnFromCameraIntent = new Intent();
            setResult(RESULT_CANCELED,returnFromCameraIntent);     
            finish();
        }
        else{
            dispatchTakePictureIntent();
        }

    }

     private void dispatchTakePictureIntent() {
        Log.i(TAG,"Dispatch Take Picture Intent");

        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent       
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go      
                File photoFile = null;
                try{
                    photoFile = createImageFile();
                }catch (IOException ex) {
                    // Error occurred while creating the File
                    ex.printStackTrace();
                    Log.i(TAG,"Error occurred while creating the File");
                }
                // Continue only if the File was successfully created
                if (photoFile != null) {
                    //  fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);  
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                    startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
                }       
        }
     }


        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            Log.i(TAG,"On Activity Result");
            File file= new File(path);  

            if (requestCode == REQUEST_TAKE_PHOTO  && resultCode == RESULT_OK && path!=null && file.length()>0) {
                        Intent returnFromCameraIntent = new Intent();
                        returnFromCameraIntent.putExtra("picturePath",path);
                        setResult(RESULT_OK,returnFromCameraIntent);  
                        finish();
                        Log.i(TAG,"Camera Closed");
                }else{
                    Log.i(TAG,"On Result CANCEL");
                    // cancelled Image capture
                    try{
                    /*delete Temperory created file*/  
                        file.delete();
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                    Intent returnFromCameraIntent = new Intent();
                    setResult(RESULT_CANCELED,returnFromCameraIntent);     
                    finish();
                    Log.i(TAG,"Image Capture Cancelled");
           }
           galleryAddPic();
     }

     private File createImageFile() throws IOException {
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",Locale.getDefault()).format(new Date());
            String imageFileName = "CAMERA_" + timeStamp + "_WA0001";

            File root = new File(Environment.getExternalStorageDirectory()
                     + File.separator + "MyApp"+ File.separator);

            if(!root.exists()){
                    root.mkdirs();  
            }

           // File storageDir = Environment.getExternalStoragePublicDirectory(
           //         Environment.DIRECTORY_PICTURES);
            File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                root      /* directory */
            );
            // Save a file: path for use with ACTION_VIEW intents
            mCurrentPhotoPath = "file:" + image.getAbsolutePath();
            path=""+image.getAbsolutePath();
            return image;
    }

     private void galleryAddPic() {
            Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            File f = new File(mCurrentPhotoPath);
            Uri contentUri = Uri.fromFile(f);
            mediaScanIntent.setData(contentUri);
            this.sendBroadcast(mediaScanIntent);
     }

     private boolean isDeviceSupportCamera() {
            if (getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
                // this device has a camera
                return true;
            } else {
                // no camera on this device
                return false;
            }
     }
}
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;

public class GalleryUtil extends Activity{
    private final static int RESULT_LOAD_GALLERY=100;
    public static final int MEDIA_TYPE_IMAGE = 1;
    private static final String TAG = "Gallery_Image";

    String mCurrentPhotoPath;
    File photoFile = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try{
            Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(i, RESULT_LOAD_GALLERY); 
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
         super.onActivityResult(requestCode, resultCode, data);
         Log.i(TAG,"On Activity Result");        
         if (requestCode == RESULT_LOAD_GALLERY && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.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 picturePath = cursor.getString(columnIndex);
            cursor.close();

                Intent returnFromGalleryIntent = new Intent();
                returnFromGalleryIntent.putExtra("picturePath",picturePath);
                setResult(RESULT_OK,returnFromGalleryIntent);     
                finish();

           }else{
                Log.i(TAG,"Image Capture Cancelled");
                Intent returnFromGalleryIntent = new Intent();
                setResult(RESULT_CANCELED,returnFromGalleryIntent);     
                finish();
           }
    }
}
将图像转换为Base64字符串:

public class Base64Utils {

    private static final String TAG = "Base64Utils";
    private String picturePath;
    private String base64;

    public Base64Utils(String picturePath) {
        this.picturePath = picturePath;
    }

    public String getPicturePath() {
        return picturePath;
    }
    public void setPicturePath(String picturePath) {
        this.picturePath = picturePath;
    }

    public String getBase64() {
        FileInputStream fis11=null;
            try {
                fis11 = new FileInputStream(picturePath);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            ByteArrayOutputStream bos11 = new ByteArrayOutputStream();
            byte[] buf = new byte[8096];
            try {
                for (int readNum; (readNum = fis11.read(buf)) != -1;) {
                    bos11.write(buf, 0, readNum); 
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        bytes = bos11.toByteArray();
        base64 = Base64.encodeToString(bytes, Base64.DEFAULT);  
        return base64;
    }

    public void setBase64(String base64) {
        this.base64 = base64;
    }
}
主要活动代码:选择或拍照,将其转换为base64字符串,并将base64字符串发送到服务器

public class CapatureImage extends Activity implements View.OnClickListener {

    private final String TAG = "CapatureImage";
    String picturePath;
    String base64 = null,   
    private ImageButton image;
    // for popup
    private PopupWindow pop;

    private final int GALLERY_ACTIVITY_CODE = 200;
    private final int CAMERA_ACTIVITY_CODE = 300;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.CapatureImage);
        configureComponent();
    }

    private void configureComponent() {
        image = (ImageButton) findViewById(R.id.image);
        image.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.image:
            initiatePopupWindow();
            break;
        case R.id.button_camera_dialog:
            Intent camera_Intent = new Intent(this.getApplicationContext(),
                    CameraUtil.class);
            pop.dismiss();
            this.startActivityForResult(camera_Intent, CAMERA_ACTIVITY_CODE);
            break;

        case R.id.button_gallery_dialog:
            Intent gallery_Intent = new Intent(this.getApplicationContext(),
                    GalleryUtil.class);
            pop.dismiss();
            this.startActivityForResult(gallery_Intent, GALLERY_ACTIVITY_CODE);
            break;

        case R.id.button_cancel_dialog:
            pop.dismiss();
            break;

        case R.id.button_remove_dialog:
            Log.i(TAG, "Remove Picture");
            image.setImageResource(R.drawable.icon_781q);
            picturePath=null;
            pop.dismiss();
            break;
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == GALLERY_ACTIVITY_CODE) {
            if (resultCode == RESULT_OK) {
                picturePath = data.getStringExtra("picturePath");   
                base64 = new Base64Utils(picturePath).getBase64();   
                //send this base64 string to server
            }
            if (resultCode == RESULT_CANCELED) {
                // Write your code if there's no result
            }
        }
        if (requestCode == CAMERA_ACTIVITY_CODE) {
            if (resultCode == RESULT_OK) {
            //  Log.i("Camera_Activity", data.toString());
                picturePath = data.getStringExtra("picturePath");
                base64 = new Base64Utils(picturePath).getBase64(); //send this base64 to server
            }
            if (resultCode == RESULT_CANCELED) {
                // Write your code if there's no result
            }
        }
    }// onActivityResult

    public void initiatePopupWindow() {
        try {
            // We need to get the instance of the LayoutInflater
            LayoutInflater inflater = (LayoutInflater) EngineerStatus_Update.this
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View layout = inflater.inflate(R.layout.dialoge_choosephoto,
                    (ViewGroup) findViewById(R.id.photo_popup));
            if (picturePath != null && !picturePath.isEmpty()) {
                Log.i(TAG, "Image Exist..Add Remove Button");
                remove = (Button) layout
                        .findViewById(R.id.button_remove_dialog);
                remove.setOnClickListener(this);
                remove.setVisibility(View.VISIBLE);
                pop = new PopupWindow(layout,
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT, true);
            } else {
                Log.i(TAG, "No Image..remove  Remove Button");
                remove = (Button) layout
                        .findViewById(R.id.button_remove_dialog);
                remove.setOnClickListener(this);
                remove.setVisibility(View.GONE);
                pop = new PopupWindow(layout,
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT, true);
            }

            // component for popup
            gallery = (Button) layout.findViewById(R.id.button_gallery_dialog);
            gallery.setOnClickListener(this);
            camera = (Button) layout.findViewById(R.id.button_camera_dialog);
            camera.setOnClickListener(this);
            cancel = (Button) layout.findViewById(R.id.button_cancel_dialog);
            cancel.setOnClickListener(this);
            pop.showAtLocation(layout, Gravity.CENTER, 0, 0);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    void displayImage(String path) {
        File imgFile = new File(path);
        if(imgFile.exists()){
            Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
            image.setImageBitmap(myBitmap);
            image.setScaleType(ScaleType.CENTER_CROP);
        }   
   }
}

我会首先将图像存储在一个文件夹中,然后通过Http post请求将其读取并发送到您的服务器。您是否了解php?如果是,我可以为您提供一个示例程序是的,我了解php。这和php有什么关系?我已经使用php来处理传入的数据并将其提交到我的服务器,并且它处于工作状态。我只想
“IMG\u 20000106\u 124322.jpg”
是动态的。Uzix SmartGlasses不“支持”动作图像捕获。我必须使用SurfaceView有没有办法将2个按钮组合成一个?