2

I have Tried lot of examples and watched many videos and done StackOverFlow, but i am not getting what i want.

1] I want to upload image path to server . 2] My php query required image of type FILE, So i cant send string. I need to upload image file path. I know how to send string and decode back to image.But i have no idea how to send image file path and then get back image.

Plz help me with this,I am in big trouble.

Things i have tried :

  private static final int PICK_FROM_CAMERA = 1;
    private static final int PICK_FROM_FILE = 2;
    private String ImgPath = null;

    private Uri mImageCaptureUri;

    private String encodedImage;

 @Override
    public void onClick(View v) {
        //  onRegisterButtonClick();


                ImgPath = null;
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_PICK);
                startActivityForResult(
                        Intent.createChooser(intent, "Complete action using"),
                        PICK_FROM_FILE);



    }

 public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.setHeaderTitle("Select The Action");
        menu.add(0, v.getId(), 0, "From Camera");
        menu.add(0, v.getId(), 0, "From Gallery");
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK)
            return;

        if (requestCode == PICK_FROM_FILE) {

            mImageCaptureUri = data.getData();

            ImgPath = getRealPathFromURI(mImageCaptureUri); // from Gallery

            Log.d("image path", ImgPath.toString());

            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 5;
            Bitmap b = BitmapFactory.decodeFile(ImgPath, options);

            if (ImgPath == null) {
                ImgPath = mImageCaptureUri.getPath(); // from File Manager
            }
            if (ImgPath != null) {
                // ivProfile.setImageBitmap(b);

                // rotate(ivProfile, 270);

                ExifInterface ei = null;
                try {
                    ei = new ExifInterface(ImgPath);
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                int orientation = ei.getAttributeInt(
                        ExifInterface.TAG_ORIENTATION,
                        ExifInterface.ORIENTATION_NORMAL);

                switch (orientation) {
                    case ExifInterface.ORIENTATION_ROTATE_180:
                        rotate(ivProfile, 180);
                        ivProfile.setImageBitmap(rotateBitmap(b, 180));

                        break;
                    case ExifInterface.ORIENTATION_ROTATE_270:
                        rotate(ivProfile, 270);
                        ivProfile.setImageBitmap(rotateBitmap(b, 270));

                        break;

                }

                try {
                    getBase64String(b);
                } catch (Exception e) {
                    e.printStackTrace();
                 /*   Utils.showAlert(this, "Please select local gallery pics.",
                            false);*/
                }
            }
        } else if (requestCode == PICK_FROM_CAMERA) {

            if (ImgPath == null) {
                ImgPath = mImageCaptureUri.getPath(); // from File Manager

            }

            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 5;
            Bitmap b = BitmapFactory.decodeFile(ImgPath, options);

            if (ImgPath != null) {
                ivProfile.setImageBitmap(b);
                // rotate(ivProfile, 270);
                try {
                    getBase64String(b);
                } catch (Exception e) {
                   // Utils.showAlert(mContext, "Out of memory", false);
                    e.printStackTrace();
                }
            }
        }

    }

    private Bitmap rotateBitmap(Bitmap b, int orientation) {
        // TODO Auto-generated method stub

        Matrix matrix = new Matrix();
        switch (orientation) {
            case ExifInterface.ORIENTATION_NORMAL:
                return b;
            case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
                matrix.setScale(-1, 1);
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                matrix.setRotate(180);
                break;
            case ExifInterface.ORIENTATION_FLIP_VERTICAL:
                matrix.setRotate(180);
                matrix.postScale(-1, 1);
                break;
            case ExifInterface.ORIENTATION_TRANSPOSE:
                matrix.setRotate(90);
                matrix.postScale(-1, 1);
                break;
            case ExifInterface.ORIENTATION_ROTATE_90:
                matrix.setRotate(90);
                break;
            case ExifInterface.ORIENTATION_TRANSVERSE:
                matrix.setRotate(-90);
                matrix.postScale(-1, 1);
                break;
            case ExifInterface.ORIENTATION_ROTATE_270:
                matrix.setRotate(-90);
                break;
            default:
                return b;
        }
        try {
            Bitmap bmRotated = Bitmap.createBitmap(b, 0, 0, b.getWidth(),
                    b.getHeight(), matrix, true);
            b.recycle();
            return bmRotated;
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
            return null;
        }

    }

    @SuppressWarnings("deprecation")
    public String getRealPathFromURI(Uri contentUri) {
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(contentUri, proj, null, null, null);
        if (cursor == null)
            return null;
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    public boolean onContextItemSelected(MenuItem item) {
        if (item.getTitle() == "From Camera") {
            ImgPath = null;
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

            File file = new File(Environment.getExternalStorageDirectory(),
                    "tmp_avatar_" + String.valueOf(System.currentTimeMillis())
                            + ".jpg");
            mImageCaptureUri = Uri.fromFile(file);

            try {
                intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
                        mImageCaptureUri);
                this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                intent.putExtra("return-data", true);

                startActivityForResult(intent, PICK_FROM_CAMERA);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (item.getTitle() == "From Gallery") {
            ImgPath = null;
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_PICK);
            startActivityForResult(
                    Intent.createChooser(intent, "Complete action using"),
                    PICK_FROM_FILE);
        } else {
            return false;
        }
        return true;
    }

    public String getBase64String(Bitmap path) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        path.compress(Bitmap.CompressFormat.JPEG, 50, baos);

        byte[] biteArray = baos.toByteArray();

        encodedImage = Base64.encodeToString(biteArray, Base64.DEFAULT);

        return encodedImage;
    }

    private void rotate(View iv, float degree) {
        final RotateAnimation rotateAnim = new RotateAnimation(0.0f, degree,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f);

        rotateAnim.setDuration(0);
        rotateAnim.setFillAfter(true);
        iv.startAnimation(rotateAnim);
    }

and then i have set encodedImage to parameters and send it to server,But it is not working

tiger
  • 413
  • 1
  • 5
  • 18
  • What exactly issue I mean any error from server side or from client ..? If you got any error thn can you please post it...? – user1140237 Jan 16 '16 at 08:09
  • Please change the subject and the text of your post. You are noth trying to upload an image path. You are trying to upload an image. – greenapps Jan 16 '16 at 12:41

1 Answers1

1

You can use HTTP mime library(Preferable 4.3.3) and HTTP post to upload the file to the server.
The PHP server will recognize the image as FILE which is required in your case.
I have created a class which helps me to upload the image or any file to my server

public class FileUploadHelper extends AsyncTask<Void, Void, Void> {

    private MultipartEntityBuilder multipartEntity;
    private String URL;

    public FileUploadHelper(String URL) {
        multipartEntity = MultipartEntityBuilder.create();
        this.URL = URL;
    }

    @SuppressLint("TrulyRandom")
    @Override
    protected Void doInBackground(Void... arg0) {
        try {
            multipartEntity.addTextBody("<YOUR STRING KEY>", "<STRING VALUE>");

            multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

            HttpClient httpclient;
            httpclient = new DefaultHttpClient();

            httpclient.getConnectionManager().closeExpiredConnections();
            HttpPost httppost = new HttpPost(URL);
            httppost.setEntity(multipartEntity.build());

            HttpResponse response = httpclient.execute(httppost);
            int responseCode = response.getStatusLine().getStatusCode();

            String serverResponse = EntityUtils.toString(response.getEntity());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void addFile(String key, File newFile) throws FileNotFoundException {
        if (newFile.exists()) {
            multipartEntity.addBinaryBody(key, newFile);
        } else {
            throw new FileNotFoundException("No file was found at the path " + newFile.getPath());
        }
    }
}

To use this class create Object of FileUploader class, then call its addFile() function and call execute() as this class extends AsyncTask. In your code you already have File object as

File file = new File(Environment.getExternalStorageDirectory(),
                    "tmp_avatar_" + String.valueOf(System.currentTimeMillis())
                            + ".jpg");

Just pass this object to addFile().

Hope this will help you

Ichigo Kurosaki
  • 3,765
  • 8
  • 41
  • 56
  • @Lchigo Kurosaki .. Thank you..But i am not getting where to put all this thing.. can u plz explain ? – tiger Jan 16 '16 at 09:39
  • In your code try this, at onAcitivtyResult() you have code like ImgPath = getRealPathFromURI(mImageCaptureUri); // from Gallery.. I think it is the path of image you choose. At this you can call this asynctask as FileUploader abc = new FIleUploader(""), then abc.addFile("string key",file object).. and then abc.execute().. – Ichigo Kurosaki Jan 16 '16 at 09:45
  • Sorry, but i m not getting things. If u have example it would be a great help – tiger Jan 16 '16 at 09:58
  • I have derived this answer from [this](http://stackoverflow.com/questions/20322528/uploading-images-to-server-android) – Ichigo Kurosaki Jan 16 '16 at 10:06