如何从图库中裁剪图像并上传到服务器

时间:2014-09-25 06:09:47

标签: android image resize-crop

我是android的新手我想从图库中选择图片并想要裁剪和发送服务器。 当我从图库中选择图像并发送到服务器。它成功上传 当我想使用裁剪方法...然后..图像打开,当我裁剪并单击确定..然后我的应用程序不幸停止

请告诉我我哪里做错了 这是我的整个活动代码

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

 }

}

这是我的logcat错误

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)

3 个答案:

答案 0 :(得分:1)

一旦参考本教程,它将对您有所帮助http://khurramitdeveloper.blogspot.in/2013/07/capture-or-select-from-gallery-and-crop.html

裁剪后,您必须将图像转换为base64位以上传到服务器。在谷歌搜索有很多关于Android中的Web服务的例子

答案 1 :(得分:0)

可能你的意图是返回空数据试试这个....为你的selectImagefromGallery

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

和OnActivityResult

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

解决imagePath使用

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

上传为您的多部门

添加文件部分
File uploadFile1 = new File(path);
multipart.addFilePart("photo1", uploadFile1);

答案 2 :(得分:0)

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