简体   繁体   中英

How to crop image from gallary and uploade to server

im new in android i want to select image from gallery and want to crop and send server. when i select image from gallery and send to Server .Its Succesfully uploaded when i want to use crop method ...Then ..Image open and and when i crop and click ok ..then My Application unfortunately stopped

please tell me where im doing wrong here is my Whole Code Of Activity

public class MainActivity extends Activity {

 private ImageView image;
 private Button uploadButton;
 private Bitmap bitmap;
 private Button selectImageButton;
 ByteArrayBody         bab1 = null;
Uri selectedImge;
 // number of images to select
 private static final int PICK_IMAGE = 1;

 /**
  * called when the activity is first created
  */
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  // find the views
  image = (ImageView) findViewById(R.id.uploadImage);
  uploadButton = (Button) findViewById(R.id.uploadButton);

  // on click select an image
  selectImageButton = (Button) findViewById(R.id.selectImageButton);
  selectImageButton.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    selectImageFromGallery();

   }
  });

  // when uploadButton is clicked
  uploadButton.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    new ImageUploadTask().execute();
   }
  });
 }

 /**
  * Opens dialog picker, so the user can select image from the gallery. The
  * result is returned in the method <code>onActivityResult()</code>
  */
 public void selectImageFromGallery() {
  Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
  intent.setType("image/*");
 // intent.setAction(Intent.ACTION_GET_CONTENT);
  intent.putExtra("crop", "true");
  intent.putExtra("outputX", 200);
  intent.putExtra("outputY", 200);
  intent.putExtra("aspectX", 1);
  intent.putExtra("aspectY", 1);
  intent.putExtra("scale", true);
  intent.putExtra(MediaStore.EXTRA_OUTPUT, selectedImge);
  intent.putExtra("outputFormat",

  Bitmap.CompressFormat.JPEG.toString());


    //  intent.putExtra("return-data", true);
      startActivityForResult(intent, 
                PICK_IMAGE);
 }



 /* startActivityForResult(Intent.createChooser(intent, "Select Picture"),
    PICK_IMAGE);
 }*/


 /**
  * Retrives the result returned from selecting image, by invoking the method
  * <code>selectImageFromGallery()</code>
  */
 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);

  if (requestCode == PICK_IMAGE && resultCode == RESULT_OK
    && null != data) {
    selectedImge = data.getData();
   String[] filePathColumn = { MediaStore.Images.Media.DATA };

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

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

   decodeFile(picturePath);

  }
 }

 /**
  * The method decodes the image file to avoid out of memory issues. Sets the
  * selected image in to the ImageView.
  * 
  * @param filePath
  */
 public void decodeFile(String filePath) {
  // Decode image size
  BitmapFactory.Options o = new BitmapFactory.Options();
  o.inJustDecodeBounds = true;
  BitmapFactory.decodeFile(filePath, o);

  // The new size we want to scale to
  final int REQUIRED_SIZE = 1024;

  // Find the correct scale value. It should be the power of 2.
  int width_tmp = o.outWidth, height_tmp = o.outHeight;
  int scale = 1;
  while (true) {
   if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
    break;
   width_tmp /= 2;
   height_tmp /= 2;
   scale *= 2;
  }

  // Decode with inSampleSize
  BitmapFactory.Options o2 = new BitmapFactory.Options();
  o2.inSampleSize = scale;
  bitmap = BitmapFactory.decodeFile(filePath, o2);

  image.setImageBitmap(bitmap);
 }




/**
  * The class connects with server and uploads the photo
  * 
  * 
  */
 class ImageUploadTask extends AsyncTask<Void, Void, String> {
  private String webAddressToPost = "http://your-website-here.com";

  // private ProgressDialog dialog;
  private ProgressDialog dialog = new ProgressDialog(MainActivity.this);

  @Override
  protected void onPreExecute() {
   dialog.setMessage("Uploading...");
   dialog.show();
  }

  @Override
  protected String doInBackground(Void... params) {
   try {
    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    HttpPost httpPost = new HttpPost("http://www.your domain.com/signup");

    MultipartEntity entity = new MultipartEntity(
      HttpMultipartMode.BROWSER_COMPATIBLE);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.JPEG, 75, bos);
    byte[] data = bos.toByteArray();
   // byte[] image=Base64.encode(data, Base64.DEFAULT);
    bab1 = new ByteArrayBody(data, "profile.jpg");
    //


    entity.addPart("fullName", new StringBody("sammywaseem"));
    entity.addPart("userName", new StringBody("samm"));
    entity.addPart("dob", new StringBody("2014-09-09"));
    entity.addPart("age", new StringBody("18"));
    entity.addPart("gender", new StringBody("M"));
    entity.addPart("interestIn", new StringBody("Both"));
    entity.addPart("toMeet", new StringBody("Women"));
    entity.addPart("email", new StringBody("mmmmmmmmii@gmail.com"));
    entity.addPart("pwd", new StringBody("123456"));

    entity.addPart("latitude", new StringBody("38.56525803"));
    entity.addPart("longitude", new StringBody("71.98562622"));
    if (bab1 != null) {
        entity.addPart("uploaded_file", bab1);
    }



    httpPost.setEntity(entity);
    HttpResponse response = httpClient.execute(httpPost,
      localContext);
    BufferedReader reader = new BufferedReader(
      new InputStreamReader(
        response.getEntity().getContent(), "UTF-8"));

    String sResponse = reader.readLine();
    return sResponse;
   } catch (Exception e) {
    // something went wrong. connection with the server error
   }
   return null;
  }

  @Override
  protected void onPostExecute(String result)
  {
   dialog.dismiss();
   Toast.makeText(getApplicationContext(), "file uploaded",
     Toast.LENGTH_LONG).show();
  }

 }

}

here is my logcat error

09-25 11:36:58.719: E/AndroidRuntime(27221): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { (has extras) }} to activity {com.example.upload_image/com.example.upload_image.MainActivity}: java.lang.NullPointerException
09-25 11:36:58.719: E/AndroidRuntime(27221):    at android.app.ActivityThread.deliverResults(ActivityThread.java:3149)
09-25 11:36:58.719: E/AndroidRuntime(27221):    at android.app.ActivityThread.handleSendResult(ActivityThread.java:3192)
09-25 11:36:58.719: E/AndroidRuntime(27221): Caused by: java.lang.NullPointerException
09-25 11:36:58.719: E/AndroidRuntime(27221):    at android.content.ContentResolver.acquireUnstableProvider(ContentResolver.java:1094)
09-25 11:36:58.719: E/AndroidRuntime(27221):    at android.content.ContentResolver.query(ContentResolver.java:354)

once refer this tutorials it will be helpful to you http://khurramitdeveloper.blogspot.in/2013/07/capture-or-select-from-gallery-and-crop.html

after cropping you have to convert the image into base64 bit to upload into server. search in google there are many examples on web services in android

Probably your intent is returning null data try this.... for your selectImagefromGallery

Intent intent = new Intent(Intent.ACTION_PICK,
    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);`

and in OnActivityResult

if (requestCode == 2) {
    Uri picUri = data.getData();
    System.out.println("picUri-----" +picUri);
    String path = getRealPathFromUri(getActivity(), picUri);
    System.out.println("PATH-----" +path);

to resolve imagePath use

public  String getRealPathFromUri(Context context, Uri contentUri) {
    Cursor cursor = null;
    try{
            String[] proj = { MediaStore.Images.Media.DATA };
            cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } 
        finally {
            if (cursor != null) {
                cursor.close();
            }
        }
}

To Upload add file part for your multipartentity

File uploadFile1 = new File(path);
multipart.addFilePart("photo1", uploadFile1);
intent = new Intent();
             intent = new   Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 

==========

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

    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == RESULT_OK) {
        if (requestCode == PICK_FROM_FILE) {
            // get the Uri for the captured image
            uri = data.getData();

            String[] prjection ={MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(uri,prjection,null,null,null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(prjection[0]);
            ImagePath = cursor.getString(columnIndex);
            cursor.close();
            FixBitmap = BitmapFactory.decodeFile(ImagePath);
            //ShowSelectedImage = (ImageView)findViewById(R.id.imageView);
            //  FixBitmap = new BitmapDrawable(ImagePath);


            ShowSelectedImage = (ImageView)findViewById(R.id.imageView);

            int nh = (int) ( FixBitmap.getHeight() * (512.0 / FixBitmap.getWidth()) );
            FixBitmap = Bitmap.createScaledBitmap(FixBitmap, 512, nh, true);

            ShowSelectedImage.setImageBitmap(BitmapFactory.decodeFile(ImagePath));
           // ShowSelectedImage.setImageBitmap(FixBitmap);
            performCrop();
        }
        // user is returning from cropping the image
        else if (requestCode == CROP_PIC) {
            // get the returned data

            Bundle extras = data.getExtras();
            // get the cropped bitmap
            thePic = extras.getParcelable("data");

            ShowSelectedImage = (ImageView)findViewById(R.id.imageView);


            ShowSelectedImage.setImageBitmap(thePic);
            //ShowSelectedImage.setImageBitmap(BitmapFactory.decodeFile(ImagePath));
           // ShowSelectedImage.setImageBitmap(FixBitmap);
        }
    }

}
    private void performCrop() {
        // take care of exceptions
        try {
            // call the standard crop action intent (the user device may not
            // support it)
            cropIntent = new Intent("com.android.camera.action.CROP");
            // indicate image type and Uri
            cropIntent.setDataAndType(uri, "image/*");
            // set crop properties
            cropIntent.putExtra("crop", "true");
            cropIntent.putExtra("scale", true);
            // indicate aspect of desired crop
            cropIntent.putExtra("aspectX", 1);
            cropIntent.putExtra("aspectY", 1);
            // indicate output X and Y
            cropIntent.putExtra("outputX", 150);
            cropIntent.putExtra("outputY", 100);
            // retrieve data on return
            cropIntent.putExtra("return-data", true);
            // start the activity - we handle returning in onActivityResult
            startActivityForResult(cropIntent, CROP_PIC);
        }
        // respond to users whose devices do not support the crop action
        catch (ActivityNotFoundException anfe) {
            Toast toast = Toast
                    .makeText(this, "This device doesn't support the crop action!", Toast.LENGTH_SHORT);
            toast.show();
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM