Aravindan K
Aravindan K

Reputation: 101

how to get captured image into app and want to upload into server?

I try to capture a image by intenting camera and set that as a profile picture in my app.

Camera captures images but picture nothing is set in profile, still blank and want to upload that picture to my server.

While reading the picture by DataInputStream it says, "The method readLine() from the type DataInputStream is deprecated".

Help me to resolve this problem.

Here is my code is:

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

Upvotes: 0

Views: 1216

Answers (2)

Rajesh Mikkilineni
Rajesh Mikkilineni

Reputation: 844

Onclick of Button Open a Camera

    //  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: private File picfile;

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

sending that Image file to server

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

u have to use these libs http://www.java2s.com/Code/Jar/h/Downloadhttpmime401jar.htm

http://www.java2s.com/Code/Jar/a/Downloadapachemime4j06jar.htm

Upvotes: 2

Harshad
Harshad

Reputation: 8014

If you are able to get path of the image then try to fetch the image form that path. There is an alternative to upload the image on server. You can convert the image into Sting using Base64 encoding and send that string via JSON to your server.

Upvotes: 0

Related Questions