2017-01-04 12 views
0

ユーザーがギャラリーから画像を選択した後に画像を切り抜きたい。ギャラリーからピックアップした後の画像を切り取る

基本的に、ユーザーがギャラリーから画像を選択すると、画像を切り抜くことができ、OKをクリックすると画像がサーバーに送られます。

ボタンをクリックすると、ギャラリーを起動するこのコードがあります。

Intent intent = new Intent(Intent.ACTION_PICK); 
intent.setType("image/*"); 
startActivityForResult(intent,RESULT_TRUE); 

次に、私はこのコードをギャラリーから選択し、firebaseにアップロードします。

@Override 
    public void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 
     if (requestCode == RESULT_TRUE && resultCode == RESULT_OK) { 
      dialog.show(); 
      Uri url = data.getData(); 
      StorageReference filepath = mstorage.child("photos").child(url.getLastPathSegment()); 
      filepath.putFile(url).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { 
       @Override 
       public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { 
        Toast.makeText(getContext(), "upload done", Toast.LENGTH_LONG).show(); 
        Uri downloadurl = taskSnapshot.getDownloadUrl(); 
        String imageUrl = downloadurl.toString(); 
        Glide.with(getContext()).load(imageUrl).centerCrop().placeholder(R.drawable.ic_menu_camera).crossFade().into(mImage1); 
        SubscriberService subscriberService = new SubscriberService(); 
        subscriberService.addItemChildList(AddImagesFragment.this, mAuth.getCurrentUser().getUid(), "images", imageUrl, place); 
        } catch (UnsupportedEncodingException e) { 
         e.printStackTrace(); 
        } catch (JSONException e) { 
         e.printStackTrace(); 
        } catch (Exception e) { 
         e.printStackTrace(); 
        } 
       } 
      }); 
     } 

画像をトリミングするコードを教えてもらえますか?

おかげ

答えて

0

このlibrary、あなたは適切な解決策を得ることがあります。

はそれがonActivityResultsにuCrop結果を処理した後、(あなたがそこを介して複数のrequestcodesを処理するために、スイッチケースを取ることができます)このonActivityResult、

case IMAGE: 
    UCrop.of(data.getData(), Uri.fromFile(new File(this.getCacheDir(), "IMG_" + System.currentTimeMillis()))) 
        .start(YourActivity.this); 
break; 

を書き、それを使用するよりも、まずあなたのGradleにuCropを追加します。

    case UCrop.REQUEST_CROP: 
        Uri imgUri = UCrop.getOutput(data); 
        if (imgUri != null) { 
         String selectedImage = imgUri.getPath(); 

         // load selectedImage into ImageView 
        } else { 
         Snackbar.make(view, R.string.str_bad_image_file, Snackbar.LENGTH_LONG) 
           .show(); 
        } 
        break; 
       case UCrop.RESULT_ERROR: 
        Snackbar.make(view, R.string.str_bad_image_file, Snackbar.LENGTH_LONG) 
          .show(); 
        break; 
+0

にこのURLを渡してください。正確には、私が上に示したコードを考慮して、ucropコードを書かなければならない場所を教えてください。 – user7327850

+0

確かに、更新された答えを見てください –

+0

ありがとう、行く? – user7327850

0

あなたは作物を実行するには、このメソッドを使用することができます: -

private void performCrop(String picUri) { 
     try { 
      //Start Crop Activity 

      Intent cropIntent = new Intent("com.android.camera.action.CROP"); 
      // indicate image type and Uri 
      File f = new File(picUri); 
      Uri contentUri = Uri.fromFile(f); 

      cropIntent.setDataAndType(contentUri, "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", 280); 
      cropIntent.putExtra("outputY", 280); 

      // retrieve data on return 
      cropIntent.putExtra("return-data", true); 
      // start the activity - we handle returning in onActivityResult 
      startActivityForResult(cropIntent, RESULT_CROP); 
     } 
     // respond to users whose devices do not support the crop action 
     catch (ActivityNotFoundException anfe) { 
      // display an error message 
      String errorMessage = "your device doesn't support the crop action!"; 
      Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT); 
      toast.show(); 
     } 
    } 

android:select image from gallery then crop that and show in an imageview

Crop an image when selected from gallery in android

+0

私はすべてのユーザーのためにサポートされているものを欲しいです。私はあなたのために作物をサポートしていないと言うことはできません:) – user7327850

+0

あなたはどのようなデバイスがサポートされていない説明できますか? – user7327850

+0

これはすべてのデバイスをサポートしますが、トーストはモバイルデバイスがトリミングの意図をサポートしていないものに対してのみです。現在、ほぼすべてのデバイスが作物行動をサポートしています。 – Nainal

0

thisチュートリアルを見てください、リンクを参照してください。..

0

このlibraryを見てください。それは基本的なクロッピング機能を提供し、多くの人々によって使用されます

0

これはよくテストされたコードなので、間違いなく動作します。画像をトリミングするには、以下のコードを使用してください:
private CropImageView img_crop;
private int CROP_RESULT = 3;

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_crop_); 
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 
    toolbar.setNavigationIcon(R.drawable.back_white); 
    toolbar.setNavigationOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      onBackPressed(); 
     } 
    }); 
    img_crop = (CropImageView) findViewById(R.id.img_crop); 
    img_crop.setInitialFrameScale(0.75f); 

    img_crop.setAnimationEnabled(true); 
    img_crop.setAnimationDuration(300); 
    img_crop.setCropMode(CropImageView.CropMode.RATIO_3_4); 
    configureDefaultImageLoader(Crop_Activity.this); 
    Intent intent = getIntent(); 
    Bundle b = intent.getExtras(); 
    String path = " "; 
    final String type = b.getString("type"); 
    path = b.getString("BitmapImage"); 
    Log.e("Crop_Uri>>", path.toString()); 
    { 
     try { 
      InputStream image_stream = null; 

      image_stream = getContentResolver().openInputStream(Uri.parse("file://" + path.toString())); 
      Bitmap bitmap1 = BitmapFactory.decodeStream(image_stream); 
      if (bitmap1 != null) { 
       bitmap1.recycle(); 
       bitmap1 = null; 
      } 
      ImageLoader.getInstance().displayImage(ImageDownloader.Scheme.FILE.wrap(path.toString()), img_crop); 
      // img_crop.setImageBitmap(bitmap1); 
      Log.e("Image//", "//" + "yes"); 
     } catch (Exception e) { 
      //handle exception 
      Log.e("ExceptionImage>>", "//" + e); 
     } 
    } 


    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
    fab.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      /* Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) 
        .setAction("Action", null).show();*/ 
      if (img_crop.getImageBitmap() != null) { 
       Bitmap crop_bitmap = img_crop.getCroppedBitmap(); 
       ByteArrayOutputStream stream = new ByteArrayOutputStream(); 

       File dest = new File(getFilename()); 
       try { 
        FileOutputStream out = new FileOutputStream(dest); 
        crop_bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); 
        out.flush(); 
        out.close(); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
       byte[] byteArray = stream.toByteArray(); 

       Intent intent = new Intent(); 
       intent.putExtra("croped_bitmap_uri", dest.getAbsolutePath()); 
       intent.setAction("ok"); 
       setResult(CROP_RESULT, intent); 
       deleteFile(); 
       finish(); 
      } else { 
       Toast.makeText(Crop_Activity.this, "Crop Images Not Processed !", Toast.LENGTH_SHORT).show(); 
      } 

     } 
    }); 
} 

public String getFilename() { 
    File myDirectory = new File(Environment.getExternalStorageDirectory(), "Konnect_Mom/Konnect_Mom_cropped_img"); 
    if (!myDirectory.exists()) { 
     myDirectory.mkdirs(); 
    } 

    String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date()); 
    String mImageName = "cropped_img" + ".jpg"; 
    String uriSting = (myDirectory.getAbsolutePath() + "/" + mImageName); 
    return uriSting; 

} 

public void deleteFile() { 
    File file = new File(Environment.getExternalStorageDirectory() + "Konnect_Mom/Konnect_Mom_cropped_img/cropped_img.jpg"); 
    if (file.exists()) { 

     file.delete(); 
    } 

} 

public static void configureDefaultImageLoader(Context ctx) { 
    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(ctx).threadPriority(Thread.NORM_PRIORITY - 2).denyCacheImageMultipleSizesInMemory().diskCacheFileNameGenerator(new Md5FileNameGenerator()).tasksProcessingOrder(QueueProcessingType.FIFO).build(); 
    ImageLoader.getInstance().init(config); 
    DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder() 
      .cacheInMemory(true) 
      .cacheOnDisk(true) 
      .showImageOnLoading(android.R.drawable.stat_sys_download) 
      .showImageForEmptyUri(android.R.drawable.ic_dialog_alert) 
      .showImageOnFail(android.R.drawable.stat_notify_error) 
      .considerExifParams(true) 
      .bitmapConfig(Bitmap.Config.RGB_565) 
      .imageScaleType(ImageScaleType.EXACTLY_STRETCHED) //filled width 
      .build(); 
} 

}

ただ、上記のコードをコピーして、 "CropActivity" と題しクラスに貼り付けます。それだけです

Intent i = new Intent(AddAChild.this, Crop_Activity.class); 
       i.putExtra("BitmapImage", filename); 
       startActivityForResult(i, CROP_RESULT); 

:その後の画像を取得するために開くアクティビティ「カメラを」または「ギャラリー」で、「onActivityResult()」メソッド内で以下のコードを配置します。あなたは行き​​たい。

関連する問題