上传后捕获图像旋转

时间:2016-09-13 11:41:10

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

我正在将图片上传到服务器,但上传到服务器后图像会旋转甚至预览显示正确。

这么多人遇到这个问题我发现这个link但是没有用。并且有很多解决方案,但我不知道如何适应我的代码。

请帮帮我。

这是我的代码

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.fonts.Text.MyTextView;
import com.generalClass.files.UploadFile;
import com.hwindiapp.driver.db.sqLite.DBConnect;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;

public class AddVehicleDocActivity extends AppCompatActivity {

    private static final int FILE_SELECT_CODE = 124;
    private Toolbar mToolbar;

    TextView text_header;
    MyTextView insuranceHTxt;
    MyTextView permitHTxt;
    MyTextView vRegHTxt;
    MyTextView insNotFoundTxt;
    MyTextView permitNotFoundTxt;
    MyTextView vRegNotFoundTxt;
    DBConnect dbConnect;

    Button insBtn;
    Button permitBtn;
    Button vRegBtn;

    LinearLayout insImgVIew;
    LinearLayout permitImgVIew;
    LinearLayout vRegImgVIew;

    String language_labels_get_frm_sqLite = "";

    String LBL_DOCUMENTS_TXT_str = "";
    String LBL_YOUR_INSURANCE_TXT_str = "";
    String LBL_WRONG_FILE_SELECTED_TXT_str = "";
    String LBL_LOADING_TXT_str = "";
    String LBL_YOUR_PERMIT_TXT_str = "";
    String LBL_VEHICLE_REG_TXT_str = "";
    String LBL_NOT_FOUND_TXT_str = "";
    String LBL_BTN_OK_TXT_str = "";
    String LBL_ERROR_TXT_str = "";
    String LBL_TRY_AGAIN_LATER_TXT_str = "";
    String LBL_DOC_UPLOAD_SUCCESS_TXT_str = "";
    String LBL_ADD_TXT_str = "";
    String LBL_EDIT_TXT_str = "";
    String LBL_SUCCESS_TXT_str = "";
    String LBL_BTN_TRIP_CANCEL_CONFIRM_TXT_str = "";
    String LBL_NOTE_UPLOAD_DOC_TXT_str = "";
    String LBL_CANCEL_TXT_str = "";

    String currentDocType = "";

    String carJson_str = "";

    String vIns = "";
    String vPermit = "";
    String vReg = "";

    android.support.v7.app.AlertDialog alertDialog;

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

        mToolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(mToolbar);

        dbConnect = new DBConnect(this, "UC_Partner_Labels.db");
        text_header = (TextView) findViewById(R.id.text_header);
        insuranceHTxt = (MyTextView) findViewById(R.id.insuranceHTxt);
        permitHTxt = (MyTextView) findViewById(R.id.permitHTxt);
        vRegHTxt = (MyTextView) findViewById(R.id.vRegHTxt);
        insNotFoundTxt = (MyTextView) findViewById(R.id.insNotFoundTxt);
        permitNotFoundTxt = (MyTextView) findViewById(R.id.permitNotFoundTxt);
        vRegNotFoundTxt = (MyTextView) findViewById(R.id.vRegNotFoundTxt);

        insImgVIew = (LinearLayout) findViewById(R.id.insImgArea);
        permitImgVIew = (LinearLayout) findViewById(R.id.permitImgArea);
        vRegImgVIew = (LinearLayout) findViewById(R.id.vRegImgArea);

        insBtn = (Button) findViewById(R.id.insBtn);
        permitBtn = (Button) findViewById(R.id.permitBtn);
        vRegBtn = (Button) findViewById(R.id.vRegBtn);

        insBtn.setOnClickListener(new setOnClickAct());
        permitBtn.setOnClickListener(new setOnClickAct());
        vRegBtn.setOnClickListener(new setOnClickAct());
        insImgVIew.setOnClickListener(new setOnClickAct());
        permitImgVIew.setOnClickListener(new setOnClickAct());
        vRegImgVIew.setOnClickListener(new setOnClickAct());

        carJson_str = getIntent().getStringExtra("CarJson");

        /* Set Labels */
        getLanguageLabelsFrmSqLite();
        /* Set Labels Finished */

        ImageView back_navigation = (ImageView) findViewById(R.id.back_navigation);
        back_navigation.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                AddVehicleDocActivity.super.onBackPressed();
            }
        });

        Log.d("carJson_str", ":" + carJson_str);

        try {
            parseCarJson(carJson_str);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void getLanguageLabelsFrmSqLite() {

        Cursor cursor = dbConnect.execQuery("select vValue from labels WHERE vLabel=\"Language_labels\"");

        cursor.moveToPosition(0);

        language_labels_get_frm_sqLite = cursor.getString(0);

        JSONObject obj_language_labels = null;
        try {
            obj_language_labels = new JSONObject(language_labels_get_frm_sqLite);
            LBL_DOCUMENTS_TXT_str = obj_language_labels.getString("LBL_DOCUMENTS_TXT");
            LBL_YOUR_INSURANCE_TXT_str = obj_language_labels.getString("LBL_YOUR_INSURANCE_TXT");
            LBL_WRONG_FILE_SELECTED_TXT_str = obj_language_labels.getString("LBL_WRONG_FILE_SELECTED_TXT");
            LBL_LOADING_TXT_str = obj_language_labels.getString("LBL_LOADING_TXT");
            LBL_YOUR_PERMIT_TXT_str = obj_language_labels.getString("LBL_YOUR_PERMIT_TXT");
            LBL_VEHICLE_REG_TXT_str = obj_language_labels.getString("LBL_VEHICLE_REG_TXT");
            LBL_NOT_FOUND_TXT_str = obj_language_labels.getString("LBL_NOT_FOUND_TXT");
            LBL_BTN_OK_TXT_str = obj_language_labels.getString("LBL_BTN_OK_TXT");
            LBL_ERROR_TXT_str = obj_language_labels.getString("LBL_ERROR_TXT");
            LBL_TRY_AGAIN_LATER_TXT_str = obj_language_labels.getString("LBL_TRY_AGAIN_LATER_TXT");
            LBL_DOC_UPLOAD_SUCCESS_TXT_str = obj_language_labels.getString("LBL_DOC_UPLOAD_SUCCESS_TXT");
            LBL_ADD_TXT_str = obj_language_labels.getString("LBL_ADD_TXT");
            LBL_EDIT_TXT_str = obj_language_labels.getString("LBL_EDIT_TXT");
            LBL_SUCCESS_TXT_str = obj_language_labels.getString("LBL_SUCCESS_TXT");
            LBL_BTN_TRIP_CANCEL_CONFIRM_TXT_str = obj_language_labels.getString("LBL_BTN_TRIP_CANCEL_CONFIRM_TXT");
            LBL_NOTE_UPLOAD_DOC_TXT_str = obj_language_labels.getString("LBL_NOTE_UPLOAD_DOC_TXT");
            LBL_CANCEL_TXT_str = obj_language_labels.getString("LBL_CANCEL_TXT");
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        if (obj_language_labels != null) {
            text_header.setText("" + LBL_DOCUMENTS_TXT_str);
            insuranceHTxt.setText("" + LBL_YOUR_INSURANCE_TXT_str);
            permitHTxt.setText("" + LBL_YOUR_PERMIT_TXT_str);
            vRegHTxt.setText("" + LBL_VEHICLE_REG_TXT_str);
            insNotFoundTxt.setText("" + LBL_NOT_FOUND_TXT_str);
            permitNotFoundTxt.setText("" + LBL_NOT_FOUND_TXT_str);
            vRegNotFoundTxt.setText("" + LBL_NOT_FOUND_TXT_str);

            insBtn.setText(LBL_ADD_TXT_str);
            permitBtn.setText(LBL_ADD_TXT_str);
            vRegBtn.setText(LBL_ADD_TXT_str);
        }

    }

    public void parseCarJson(String carJson) throws JSONException {

        JSONObject obj_profile = new JSONObject(carJson);

        vIns = obj_profile.getString("vInsurance");
        vPermit = obj_profile.getString("vPermit");
        vReg = obj_profile.getString("vRegisteration");

        if (vIns == null || vIns.equals("")) {
            insNotFoundTxt.setVisibility(View.VISIBLE);
        } else {
            setDocView(0);
        }

        if (vPermit == null || vPermit.equals("")) {
            permitNotFoundTxt.setVisibility(View.VISIBLE);
        } else {
            setDocView(1);
        }

        if (vReg == null || vReg.equals("")) {
            vRegNotFoundTxt.setVisibility(View.VISIBLE);
        } else {
            setDocView(2);
        }
    }

    public void setDocView(int id) {
        if (id == 0) {
            insNotFoundTxt.setVisibility(View.GONE);
            insBtn.setText(LBL_EDIT_TXT_str);
            insImgVIew.setVisibility(View.VISIBLE);

        } else if (id == 1) {
            permitNotFoundTxt.setVisibility(View.GONE);
            permitBtn.setText(LBL_EDIT_TXT_str);
            permitImgVIew.setVisibility(View.VISIBLE);

        } else if (id == 2) {
            vRegNotFoundTxt.setVisibility(View.GONE);
            vRegBtn.setText(LBL_EDIT_TXT_str);
            vRegImgVIew.setVisibility(View.VISIBLE);
        }
    }

    public class setOnClickAct implements View.OnClickListener {

        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.insBtn:
                    currentDocType = "vInsurance";
                    chooseFIle();
                    break;

                case R.id.permitBtn:
                    currentDocType = "vPermit";
                    chooseFIle();
                    break;

                case R.id.vRegBtn:
                    currentDocType = "vRegisteration";
                    chooseFIle();
                    break;

                case R.id.insImgArea:
                    openDocument(vIns);
                    break;

                case R.id.permitImgArea:
                    openDocument(vPermit);
                    break;

                case R.id.vRegImgArea:
                    openDocument(vReg);
                    break;
            }
        }
    }

    public void openDocument(String documentName) {
        Log.d("Open doc","::"+CommonUtilities.SERVER_URL_VEHICLE_DOCS + getIntent().getStringExtra("iDriverVehicleId") + "/" + documentName);
        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(CommonUtilities.SERVER_URL_VEHICLE_DOCS + getIntent().getStringExtra("iDriverVehicleId") + "/" + documentName));
        startActivity(browserIntent);
    }

    public void chooseFIle() {
        boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        if (isKitKat) {
            Intent intent = new Intent();
            intent.setType("*/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(intent, FILE_SELECT_CODE);

        } else {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            startActivityForResult(intent, FILE_SELECT_CODE);
        }
    }

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

        if (resultCode == RESULT_OK) {

            if (requestCode == FILE_SELECT_CODE) {
                Uri uri = data.getData();

//                Log.d("Path", "::" + uri.getPath());
//                Log.d("Path", "::" + getPath(uri));

                String filePath = "";

                filePath = (getPath(uri) == null) ? uri.getPath() : getPath(uri);

//                Log.d("Ext", ":" + getFileExt(filePath));

                final ArrayList<String[]> paramsList = new ArrayList<>();
                paramsList.add(generateImageParams("iDriverVehicleId", "" + getIntent().getStringExtra("iDriverVehicleId")));
                paramsList.add(generateImageParams("type", "UploadVehicleDoc"));
                paramsList.add(generateImageParams("iDriverId", getIntent().getStringExtra("UserID")));
                paramsList.add(generateImageParams("DocUploadType", currentDocType));

                if (getFileExt(filePath).equalsIgnoreCase("jpg") || getFileExt(filePath).equalsIgnoreCase("gif") || getFileExt(filePath).equalsIgnoreCase("png")
                        || getFileExt(filePath).equalsIgnoreCase("jpeg") || getFileExt(filePath).equalsIgnoreCase("bmp") || getFileExt(filePath).equalsIgnoreCase("pdf")
                        || getFileExt(filePath).equalsIgnoreCase("doc") || getFileExt(filePath).equalsIgnoreCase("docx")) {


                    File selectedFile = new File(filePath);

                    if (selectedFile != null) {
                        android.support.v7.app.AlertDialog.Builder alertDialogBuilder = new android.support.v7.app.AlertDialog.Builder(
                                AddVehicleDocActivity.this);

                        alertDialogBuilder.setTitle(LBL_BTN_TRIP_CANCEL_CONFIRM_TXT_str);

                        final String finalFilePath = filePath;
                        alertDialogBuilder
                                .setMessage(selectedFile.getName() + "\n" + LBL_NOTE_UPLOAD_DOC_TXT_str)
                                .setCancelable(true)
                                .setNegativeButton(LBL_CANCEL_TXT_str, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        alertDialog.dismiss();
                                    }
                                })
                                .setPositiveButton(LBL_BTN_OK_TXT_str, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        alertDialog.dismiss();
                                        new uploadDocument(finalFilePath, currentDocType + "." + getFileExt(finalFilePath), paramsList).execute();
                                    }
                                });
                        alertDialog = alertDialogBuilder.create();
                        alertDialog.show();
                    } else {
                        showMessage(LBL_ERROR_TXT_str, LBL_TRY_AGAIN_LATER_TXT_str);
                    }
                } else {
//                    showErrorOnSelection();
                    showMessage(LBL_ERROR_TXT_str, LBL_WRONG_FILE_SELECTED_TXT_str);
                }
            }
        }
    }

    public String[] generateImageParams(String key, String content) {
        String[] tempArr = new String[2];
        tempArr[0] = key;
        tempArr[1] = content;

        return tempArr;
    }

    public class uploadDocument extends AsyncTask<String, String, String> {
        String selectedPath;
        String responseString = "";
        ProgressDialog myPDialog;

        String temp_File_Name = "";
        ArrayList<String[]> paramsList;

        public uploadDocument(String selectedPath, String temp_File_Name, ArrayList<String[]> paramsList) {
            this.selectedPath = selectedPath;
            this.temp_File_Name = temp_File_Name;
            this.paramsList = paramsList;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            myPDialog = new ProgressDialog(AddVehicleDocActivity.this, R.style.DialogTheme_custom);
            myPDialog.setMessage("" + LBL_LOADING_TXT_str);
            myPDialog.setCancelable(false);
            myPDialog.setCanceledOnTouchOutside(false);
            myPDialog.show();
        }

        @Override
        protected String doInBackground(String... strings) {

            responseString = new UploadFile().uploadImageAsFile(selectedPath, temp_File_Name, "vFile", paramsList);
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            myPDialog.dismiss();

            Log.d("responseString", "::" + responseString);
            if (responseString != null && !responseString.equals("")) {

                try {
                    JSONObject obj_temp = new JSONObject(responseString);
                    String action_str = obj_temp.getString("Action");
                    String fileName_str = obj_temp.getString("vFileName");

                    if (action_str.equals("1")) {
                        showMessage(LBL_SUCCESS_TXT_str, LBL_DOC_UPLOAD_SUCCESS_TXT_str);

                        JSONObject obj_CarJson = new JSONObject(carJson_str);
                        if (currentDocType.equals("vInsurance")) {
                            obj_CarJson.remove("vInsurance");
                            obj_CarJson.put("vInsurance", fileName_str);
                            vIns = fileName_str;
                            setDocView(0);
                        } else if (currentDocType.equals("vPermit")) {
                            obj_CarJson.remove("vPermit");
                            obj_CarJson.put("vPermit", fileName_str);
                            vPermit = fileName_str;
                            setDocView(1);
                        } else if (currentDocType.equals("vRegisteration")) {
                            obj_CarJson.remove("vRegisteration");
                            obj_CarJson.put("vRegisteration", fileName_str);
                            vReg = fileName_str;
                            setDocView(2);
                        }
                        obj_CarJson.remove("eStatus");
                        obj_CarJson.put("eStatus", "Inactive");

                        carJson_str = obj_CarJson.toString();

                        Intent setData = new Intent();
                        setData.putExtra("CarJson", carJson_str);
                        setData.putExtra("DriverProfileData", obj_temp.getString("DriverProfileData").toString());
                        setData.putExtra("iDriverVehicleId", "" + getIntent().getStringExtra("iDriverVehicleId"));
                        setResult(RESULT_OK, setData);
//                        Driver_main_profile.updated_json_responseString_profile = obj_profileJson.toString();
//
//                        Driver_main_profile.driverDocUpdated = true;

                    } else {
                        showMessage(LBL_ERROR_TXT_str, LBL_TRY_AGAIN_LATER_TXT_str);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    showMessage(LBL_ERROR_TXT_str, LBL_TRY_AGAIN_LATER_TXT_str);
                }


            } else {
                showMessage(LBL_ERROR_TXT_str, LBL_TRY_AGAIN_LATER_TXT_str);
            }
        }
    }

    public String getFileExt(String fileName) {
        return fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
    }

    public String getPath(Uri uri) {
        String[] filePathColumn = {MediaStore.Images.Media.DATA};

        Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);

        if (cursor != null) {
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex);
            cursor.close();

            return filePath;
        } else {
            return null;
        }
    }

    public void showMessage(String title_str, String content_str) {
        android.support.v7.app.AlertDialog.Builder alertDialogBuilder = new android.support.v7.app.AlertDialog.Builder(
                AddVehicleDocActivity.this);

        alertDialogBuilder.setTitle(title_str);
        alertDialogBuilder
                .setMessage(content_str)
                .setCancelable(true)
                .setPositiveButton(LBL_BTN_OK_TXT_str, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        alertDialog.dismiss();
                    }
                });
        alertDialog = alertDialogBuilder.create();
        alertDialog.show();

    }
}

这是我的上传代码

 public class UploadFile {

    public String uploadImageAsFile(String sourceFileUri, String fileName, String imageParamKey, ArrayList<String[]> params) {


        ExifInterface exif = null;     //Since API Level 5
        try {
            exif = new ExifInterface(sourceFileUri);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String exifImage = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
        String responseString = "";
        InputStream inputStream;

        try {
            inputStream = new FileInputStream(new File(exifImage));
            byte[] data;
            try {
                data = convertToByteArray(inputStream);

                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(CommonUtilities.SERVER_URL);

                InputStreamBody inputStreamBody = new InputStreamBody(new ByteArrayInputStream(data), fileName);
                MultipartEntity multipartEntity = new MultipartEntity(/*HttpMultipartMode.BROWSER_COMPATIBLE,"9999999999", Charset.defaultCharset()*/);


                for (int i = 0; i < params.size(); i++) {
                    String[] paramsArr = params.get(i);
                    multipartEntity.addPart(paramsArr[0], new StringBody(paramsArr[1]));
                }

                ContentBody cbFile = new FileBody(new File(exifImage)/*, "multipart/form-data"*/);
                multipartEntity.addPart(imageParamKey, cbFile);

                httpPost.setEntity(multipartEntity);

//                httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Test Browser");
//                httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
//                httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, org.apache.http.client.params.CookiePolicy.BROWSER_COMPATIBILITY);
//                httpPost.setHeader("Content-Type", "multipart/form-data");
//                httpPost.setHeader("Content-Type", "image/png");
//                httpPost.setHeader("Connection", "Keep-Alive");
//                httpPost.setRequestProperty("ENCTYPE", "multipart/form-data");
//                httpPost.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
//                httpPost.addHeader("Content-Type", "multipart/form-data;charset=UTF-8;boundary=654654");
//                httpPost.setHeader("Connection", "Keep-Alive");
//                httpPost.setHeader("ENCTYPE", "multipart/form-data");


                HttpResponse httpResponse = httpClient.execute(httpPost);

                // Handle response back from script.
                if (httpResponse != null) {

                    Log.d("success", "success:" + httpResponse.toString());
                    responseString = EntityUtils.toString(httpResponse.getEntity());

                } else { // Error, no response.

                    Log.d("Failed", "failed:" + httpResponse.toString());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }

        return responseString;
    }

    private byte[] convertToByteArray(InputStream inputStream) throws IOException {

        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        int next = inputStream.read();
        while (next > -1) {
            bos.write(next);
            next = inputStream.read();
        }

        bos.flush();

        return bos.toByteArray();
    }

    /**
     * @param encodedString
     * @return bitmap (from given string)
     */
    public Bitmap StringToBitMap(String encodedString){
        try{
            byte [] encodeByte=Base64.decode(encodedString, Base64.DEFAULT);
            Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
            return bitmap;
        }catch(Exception e){
            e.getMessage();
            return null;
        }
    }



}

2 个答案:

答案 0 :(得分:0)

上传后您不应该旋转图像。你需要先旋转它。预览是正确的可能是因为您在显示时尊重Exif值。但是服务器并不是。

您需要根据它的exif旋转旋转图像:

https://stackoverflow.com/a/20480741/3410697

只有这样你才能把它上传到服务器

答案 1 :(得分:0)

在获得图像路径的地方调用此函数

public void setImage(String _path) {
    int orientation = CustomImageUtil.getExifOrientation(_path);
    BitmapFactory.Options resample = new BitmapFactory.Options();
    resample.inSampleSize = 4;
    Bitmap bitmap = BitmapFactory.decodeFile(_path, resample);
    if (orientation == 90) {
        bitmap = CustomImageUtil.rotate(bitmap, 90);
    } else if (orientation == 180) {
        bitmap = CustomImageUtil.rotate(bitmap, 180);
    } else if (orientation == 270) {
        bitmap = CustomImageUtil.rotate(bitmap, 270);
    }

    // use your bitmap here


}

CustomImageUtil.class:

 public class CustomImageUtil {



public static  String getRealPathFromURI(Context context,Uri contentURI) {
    String result;
    Cursor cursor = context.getContentResolver().query(contentURI, null, null, null, null);
    if (cursor == null) { // Source is Dropbox or other similar local file path
        result = contentURI.getPath();
    } else { 
        cursor.moveToFirst(); 
        int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
        result = cursor.getString(idx);
        cursor.close();
    }
    return result;
}

// method for bitmap to base64
public static String encodeTobase64(Bitmap image) {
    Bitmap immage = image;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    immage.compress(Bitmap.CompressFormat.PNG, 60, baos);
    byte[] b = baos.toByteArray();
    String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);

    Log.d("Image Log:", imageEncoded);
    return imageEncoded;



}

/**
 * getExifOrientation -- Roate the image on the right angel
 * @param filepath -- path of the file to be rotated
 * @return
 */
public static int getExifOrientation(String filepath) {

    int degree = 0;
    ExifInterface exif = null;
    try {
        exif = new ExifInterface(filepath);
    } catch (IOException ex) {ex.printStackTrace();
    }
    if (exif != null) {
        int orientation = exif.getAttributeInt(
                ExifInterface.TAG_ORIENTATION, -1);
        if (orientation != -1) {
            // We only recognize a subset of orientation tag values.
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }

        }
    }
    return degree;
}



// Rotates the bitmap by the specified degree.
// If a new bitmap is created, the original bitmap is recycled.
public static Bitmap rotate(Bitmap b, int degrees) {
    if (degrees != 0 && b != null) {
        Matrix m = new Matrix();
        m.setRotate(degrees, (float) b.getWidth() / 2,
                (float) b.getHeight() / 2);
        try {
            Bitmap b2 = Bitmap.createBitmap(b, 0, 0, b.getWidth(),
                    b.getHeight(), m, true);
            if (b != b2) {
                b.recycle();
                b = b2;
            }
        } catch (OutOfMemoryError ex) {ex.printStackTrace();
        }
    }
    return b;
}


 }

将位图转换为Uri

public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}