从相机捕获图像并将其直接发送到服务器

时间:2014-01-04 23:37:16

标签: android android-intent camera android-camera-intent

我正在尝试编写一个小代码,允许我从相机中取出后直接发送图片,我的意思是当我从相机拍照时,这张图片将被直接发送到服务器而不存储在我的电话或在SD卡,所以我做了这个代码,但我不知道它是否正确,因为实际上它显示我很多消息错误,但我不知道问题出在哪里或者有人可以告诉我在哪里可以找到类似的代码,

// Upload Direct From Camera
camButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent_gallery = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        intent_gallery.putExtra( MediaStore.EXTRA_OUTPUT, SERVER_URL + "uploadFromCamera.php" );
        startActivityForResult(intent_gallery, SELECT_IMAGE);
    }
});
...

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_IMAGE) {
            Uri selectedImageUri       = data.getData();
            String selectedImagePath   = getPath( selectedImageUri );
            String url                 = SERVER_URL + "uploadFromCamera.php";

            if ( selectedImagePath != null ) {
                //Send to server
            }
        }
    }           
}

public String getPath(Uri uri) {
    String result = null;
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
    if(cursor.moveToFirst()){;
       int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
       result = cursor.getString(column_index);
    }
    cursor.close();
    return result;
}

3 个答案:

答案 0 :(得分:1)

这是将图像上传到PHP服务器的示例代码:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
        case 1:
            if(data != null && data.getData() != null){
                Uri _uri = data.getData();

                if (_uri != null) {
                    Cursor cursor = getContentResolver().query(_uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
                    cursor.moveToFirst();
                    final String imageFilePath = cursor.getString(0);
                    Log.w("","image url : "+imageFilePath);
                    new Thread(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            UploadFile upload = new UploadFile(UserID.getText().toString(), SignUp.this);
                            upload.uploadFile(imageFilePath);

                        }
                    }).start();
                    innitSignUp();
                }
            }

            break;

        default:
            break;
        }

//// ------------ uploadfile code:

public class UploadFile {
    private String upLoadServerUri = null;
    String t_name;
    Context context;

    public UploadFile(String filepath, Context context) {
        t_name = filepath;
        this.context = context;
    }

    public int uploadFile(String sourceFileUri) {

        String fileName = sourceFileUri;
        int serverResponseCode = 200;
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        File sourceFile = new File(sourceFileUri);

        if (!sourceFile.isFile()) {
            return 0;
        } else {
            try {

                // open a URL connection to the Servlet
                FileInputStream fileInputStream = new FileInputStream(
                        sourceFile);
                upLoadServerUri = context.getString(R.string.httpUploadImage);

                URL url = new URL(upLoadServerUri);

                // Open a HTTP connection to the URL
                conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true); // Allow Inputs
                conn.setDoOutput(true); // Allow Outputs
                conn.setUseCaches(false); // Don't use a Cached Copy
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                conn.setRequestProperty("Content-Type",
                        "multipart/form-data;boundary=" + boundary);
                conn.setRequestProperty("uploaded_file", fileName);

                dos = new DataOutputStream(conn.getOutputStream());

                dos.writeBytes(twoHyphens + boundary + lineEnd);
                 dos.writeBytes("Content-Disposition: form-data; name='uploaded_file';filename="+"'"
                 + t_name + ".jpg'" + lineEnd);

                dos.writeBytes(lineEnd);

                // create a buffer of maximum size
                bytesAvailable = fileInputStream.available();

                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];

                // read file and write it into form...
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                while (bytesRead > 0) {

                    dos.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                }

                // send multipart form data necesssary after file data...
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                // Responses from the server (code and message)
                serverResponseCode = conn.getResponseCode();
                String serverResponseMessage = conn.getResponseMessage();

                Log.i("uploadFile", "HTTP Response is : "
                        + serverResponseMessage + ": " + serverResponseCode);

                // close the streams
                fileInputStream.close();
                dos.flush();
                dos.close();

            } catch (MalformedURLException ex) {

                Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
            } catch (Exception e) {

            } // End else block
        }
        return serverResponseCode;
    }



}

答案 1 :(得分:0)

将此方法与传递周长和文件名一起使用时,必须设置username.jpg“ .png / .jpg之类的图像格式”

public static String mediaFileUriString(Context context, Uri finalPicUri, 
String filename) {

        try {
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursor cursor = context.getContentResolver().query(finalPicUri,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            return picturePath;
        } catch (Exception e) {
            return AppConstant.storagePath.getAbsolutePath().concat("/").concat(filename);
        }
    }

答案 2 :(得分:-2)

我做了这个教程,希望它有所帮助,我使用Retrofit将其发送到服务器

    private void dispatchTakePictureIntent() {
    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();
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(MainActivity.this,
                    "com.example.cedancp.uploadimage",
                    photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, MainActivity.RC_CAPTURE_IMAGE);
        }
    }
}


private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
        imageFileName,  /* prefix */
        ".jpg",         /* suffix */
        storageDir      /* directory */
);

currentImagePath = image.getPath(); //Save current image path to send later to server
return image;

}

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {    
    switch (requestCode) {
            case RC_CAPTURE_IMAGE:
                Log.i(TAG, "RESULT CODE " + resultCode);
                if (resultCode == RESULT_OK) {
                    if(currentImagePath.length() > 0)
                    sendImageToServer(currentImagePath);
                }else{
                    currentImagePath = "";
                    Toast.makeText(MainActivity.this,"Error capturing image",Toast.LENGTH_SHORT).show();
                }
                break;
 default:
            super.onActivityResult(requestCode, resultCode, data);
            break;
    }
}

private void sendImageToServer(String imagePath, final boolean camera){
    final File image = new File(imagePath);
    if(image != null) {
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), image);
        MultipartBody.Part body = MultipartBody.Part.createFormData("image", image.getName(), requestFile);
        Call<JsonObject> call = api.uploadImage(body);
        call.enqueue(new Callback<JsonObject>() {
            @Override
            public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                if(response.code() == 200){
                    Toast.makeText(MainActivity.this,"Image Uploaded!",Toast.LENGTH_SHORT).show();
                    if(camera){ //Delete image if it was taken from camera
                        image.delete(); 
                    }
                }
            }

            @Override
            public void onFailure(Call<JsonObject> call, Throwable t) {

            }
        });
    }
}

披露:此链接指向我自己的博客。

Tutorial upload image to server

相关问题