Java 如何将捕获的图像导入应用程序并希望上载到服务器?

Java 如何将捕获的图像导入应用程序并希望上载到服务器?,java,android,Java,Android,我试着用相机拍摄一幅图像,并在我的应用程序中将其设置为个人资料图片 摄像头捕获图像,但图片配置文件中未设置任何内容,仍然为空,希望将该图片上载到我的服务器 当通过DataInputStream读取图片时,它会说,“DataInputStream类型中的readLine()方法已被弃用” 帮我解决这个问题 以下是我的代码: public void settings(){ AlertDialog.Builder alertDialog2 = new Aler

我试着用相机拍摄一幅图像,并在我的应用程序中将其设置为个人资料图片

摄像头捕获图像,但图片配置文件中未设置任何内容,仍然为空,希望将该图片上载到我的服务器

当通过DataInputStream读取图片时,它会说,“DataInputStream类型中的readLine()方法已被弃用”

帮我解决这个问题

以下是我的代码:

    public void settings(){

                AlertDialog.Builder alertDialog2 = new AlertDialog.Builder(SignUp.this);

                alertDialog2.setTitle("");

                alertDialog2.setMessage("Please select an image..");

                alertDialog2.setIcon(R.drawable.act_camera);

                alertDialog2.setPositiveButton("CAMERA.",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                condition="from_camera";
                                pd = ProgressDialog.show(SignUp.this, "", "Please wait...", true);
                                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);            
                                startActivityForResult(cameraIntent, CAM_REQUREST);     
                            }
                        });

                        alertDialog2.setNegativeButton("GALLERY.",
                        new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int which) {
                                condition="from_gallery";
                                pd = ProgressDialog.show(SignUp.this, "", "Please wait...", true);
                                Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                                startActivityForResult(i, RESULT_LOAD_IMAGE);


                            }
                        });

                alertDialog2.show();

                                } 

            @JavascriptInterface

        public void showCustomAlert() {
            // TODO Auto-generated method stub


             Context context = getApplicationContext();
                // Create layout inflator object to inflate toast.xml file
                LayoutInflater inflater = getLayoutInflater();

                // Call toast.xml file for toast layout 
                View toastRoot = inflater.inflate(R.layout.toast, null);

                Toast toast = new Toast(context);

                // Set layout to toast 
                toast.setView(toastRoot);
                toast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL,
                        0, 0);
                toast.setDuration(Toast.LENGTH_LONG);
                toast.show();




        }

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

           if (requestCode == CAM_REQUREST) 
           {  
               bitmap_profile_image = (Bitmap) data.getExtras().get("data");  
               imagepath =  ImageWrite(bitmap_profile_image); 
               pd.dismiss();
           } 

         else if (requestCode == RESULT_LOAD_IMAGE && 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);
               Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
               cursor.close();
               john.setImageBitmap(thumbnail); 
               System.out.println("Step--------->1");
               pd1 = ProgressDialog.show(SignUp.this, "", "Please wait...", true);
               System.out.println("Step--------->1");
               imagepath =  ImageWrite(thumbnail);
               pd1.dismiss();
               pd.dismiss();
               Log.w("path of image from gallery......*******.....", picturePath+"");


           } 
         else{


         }    

           Imageuploading();  


          }

        public String ImageWrite(Bitmap bitmap1)
        {
            //pd = ProgressDialog.show(context,null, "Please wait...",true);
             String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
                OutputStream outStream = null;
                File file = new File(extStorageDirectory, "slectimage.PNG");

                try 
                {

                    outStream = new FileOutputStream(file);
                    bitmap1.compress(Bitmap.CompressFormat.PNG, 100, outStream);
                    outStream.flush();
                    outStream.close();
                    pd.dismiss();


                } 
                catch (FileNotFoundException e) 
                {
                    e.printStackTrace();
                    pd.dismiss();

                } catch (IOException e) 
                {
                    e.printStackTrace();
                    pd.dismiss();

                }
                String imageInSD = "/sdcard/slectimage.PNG";
            pd.dismiss();
                return imageInSD;

        }

        protected void Imageuploading() {
            // TODO Auto-generated method stub
            pd1 = ProgressDialog.show(this,null, "Please wait...",true);
             try{


                    Log.e("SANGUUU", "dfdf");

                    HttpURLConnection connection = null;
                    DataOutputStream outputStream = null;
                    String pathToOurFile = (String) imagepath; 
                    System.out.println("patho our file"+pathToOurFile);
                    //String urlServer = "http://demo.cogzideltemplates.com/client/snapchat-clone/index.php/user/image_upload";
                    String urlServer = "http://demo.cogzidel.com/sedio/mobile/image_upload";
                    String lineEnd = "\r\n";
                    String twoHyphens = "--";
                    String boundary =  "*****";

                    int bytesRead, bytesAvailable, bufferSize;
                    byte[] buffer;
                    int maxBufferSize = 1*1024*1024;

                    FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile));

                    URL url = new URL(urlServer);
                    connection = (HttpURLConnection) url.openConnection();

                    // Allow Inputs & Outputs
                    connection.setDoInput(true);
                    connection.setDoOutput(true);
                    connection.setUseCaches(false);

                    // Enable POST method
                    connection.setRequestMethod("POST");

                    connection.setRequestProperty("Connection", "Keep-Alive");
                    connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

                    outputStream = new DataOutputStream( connection.getOutputStream() );
                    outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                    outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd);
                    outputStream.writeBytes(lineEnd);

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

                    // Read file
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                    while (bytesRead > 0)
                    {
                        System.out.println("test");
                    outputStream.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                    }

                    outputStream.writeBytes(lineEnd);
                    outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                    connection.getResponseCode();
                    String serverResponseMessage = connection.getResponseMessage();
                    URL serverResponseMessage1 = connection.getURL();
                    System.out.println("url value"+serverResponseMessage1);
                    connection.getResponseMessage();
                //  Toast.makeText(getApplicationContext(),  serverResponseMessage, Toast.LENGTH_LONG).show();
                    System.out.println("image"+serverResponseMessage);
                    int len=connection.getContentLength();
                    System.out.println("Length of url--->1"+len);                
                    fileInputStream.close();
                    outputStream.flush();
                    outputStream.close();

                    DataInputStream inputStream1 = null;
                    inputStream1 = new DataInputStream (connection.getInputStream());
                    String str="";
                    String Str1_imageurl="";

                    while ((  str = inputStream1.readLine()) != null)  // here getting deprecated error
                    {
                       Log.e("Debug","Server Response "+str);

                        Str1_imageurl = str;
                        Log.e("Debug","Server Response String imageurl"+str);
                    }
                    inputStream1.close();
                    System.out.println("image url"+Str1_imageurl);
            //      Toast.makeText(getApplicationContext(),  Str1_imageurl, Toast.LENGTH_LONG).show();
                    pd1.dismiss();
                       stry=Str1_imageurl.trim();


                         }
                         catch(Exception e){

                                e.printStackTrace();

                         }

        }

     //create helping method cropCapturedImage(Uri picUri)
     public void cropCapturedImage(Uri picUri){
      //call the standard crop action intent
      Intent cropIntent = new Intent("com.android.camera.action.CROP");
      //indicate image type and Uri of image
      cropIntent.setDataAndType(picUri, "image/*");
      //set crop properties
      cropIntent.putExtra("crop", "true");
      //indicate aspect of desired crop
      cropIntent.putExtra("aspectX", 1);
      cropIntent.putExtra("aspectY", 1);
      //indicate output X and Y
      cropIntent.putExtra("outputX", 256);
      cropIntent.putExtra("outputY", 256);
      //retrieve data on return
      cropIntent.putExtra("return-data", true);
      //start the activity - we handle returning in onActivityResult
      startActivityForResult(cropIntent, 2);
     }

如果您能够获取图像的路径,则尝试从该路径获取图像。
还有一种方法可以在服务器上上载图像。您可以使用Base64编码将图像转换为Sting,并通过JSON将该字符串发送到服务器

点击按钮打开摄像机

    //  Util.TEMP_PHOTO_FILE_NAME is String file name ; 

            String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            mFileTemp = new File(Environment
                    .getExternalStorageDirectory(),
                    Util.TEMP_PHOTO_FILE_NAME);
        } else {
            mFileTemp = new File(getApplicationContext().getFilesDir(),
                    Util.TEMP_PHOTO_FILE_NAME);
        }
        intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        try {
            Uri mImageCaptureUri = null;
            // String state = Environment.getExternalStorageState();
            if (mFileTemp == null) {
                System.out.println("no file found");
            } else {
                System.out.println("file found");

            }
            if (Environment.MEDIA_MOUNTED.equals(state)) {
                mImageCaptureUri = Uri.fromFile(mFileTemp);
            } else {
                mImageCaptureUri = InternalStorageContentProvider.CONTENT_URI;
            }
            intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
                    mImageCaptureUri);
            intent.putExtra("return-data", true);
            startActivityForResult(intent, SELECT_CAMERA_IMAGE_REQUEST);
            /*
             * Intent cameraIntent = new
             * Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
             * startActivityForResult(cameraIntent,
             * SELECT_CAMERA_IMAGE_REQUEST);
             */
        } catch (ActivityNotFoundException e) {

            Log.d("Tag", "cannot take picture", e);
        }
onActivityResult: 私有文件

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK) {
      if (requestCode == SELECT_CAMERA_IMAGE_REQUEST
                && resultCode == Activity.RESULT_OK) {
            picfile = mFileTemp;
            postFlagFileCheck = 1;
            bitmap_postImage = BitmapFactory.decodeFile(picfile
                    .getAbsolutePath());
            setImagePreview(bitmap_postImage);
        }
  }
正在将该映像文件发送到服务器

        HttpClient httpclient;
        httpclient = HttpClientSingalTon.getHttpClienttest();
        HttpPost httpPostRequest = new HttpPost(URL);
        // Try This
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        MultipartEntity mpEntity = new MultipartEntity();
        ContentBody cbFile = new FileBody(yourimagefile, "image/jpeg");
        mpEntity.addPart("file", cbFile); 
        httpPostRequest.setEntity(mpEntity);
        HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
你必须使用这些LIB


请告诉我如何获取图像的路径?您已经在使用内容解析器。您可以参考以下答案以获取最新捕获的图像路径。将图像上载到服务器您可以在此处查看我的答案@nitimisra您可以检查我的摄像头捕获代码吗?是这样吗。?我可以从gallery/SDcard拍摄图像,但我仍然可以捕获和预览我的图像,如果我单击“确定”,则不会发生任何事情,它将返回应用程序,但个人资料图片不会更改。