【问题标题】:Crop image after picking up from gallery android [duplicate]从画廊 android 拾取后裁剪图像 [重复]
【发布时间】:2017-05-18 06:50:17
【问题描述】:

想要在用户从图库中挑选图像后裁剪图像。

所以基本上当用户从图库中选择图像时,他应该能够裁剪它,当他点击确定时,图像应该被发送到服务器。

点击按钮时,我有这段代码可以启动画廊。

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

有人可以帮我提供裁剪图像的代码吗?

谢谢

【问题讨论】:

    标签: android android-gallery


    【解决方案1】:

    看看这个library,也许你会得到一个合适的解决方案。

    首先将 uCrop 添加到您的 Gradle,然后 要使用它,请编写此 onActivityResult,

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

    之后在 onActivityResults 中处理 uCrop Result 为(您可以使用 switch case 来处理那里的多个请求代码):

                     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;
    

    【讨论】:

    • 考虑到我上面显示的代码,你能告诉我究竟在哪里编写 ucrop 代码
    • 当然,看看更新的答案
    • 谢谢,但我很困惑我现有的代码会去哪里?
    • 我认为你应该尝试用这个替换/修改你的代码。您将能够从您的代码中获取图像,然后从上面的代码中您将能够处理裁剪。
    • 你能看看我遇到的新问题吗stackoverflow.com/questions/41476946/…
    【解决方案2】:

    这是一个经过良好测试的代码,所以它肯定会工作。尝试使用下面的代码来裁剪图像:
    私人 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”的类中。之后,在您打开“Camera”或“Gallery”以获取图像的 Activity 中,将以下代码放入“onActivityResult() " 方法:

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

    就是这样。你很高兴。

    【讨论】:

      【解决方案3】:

      您可以使用此方法进行裁剪:-

      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

      【讨论】:

      • 我想要所有用户都支持的东西。我不能说我们不支持你的裁剪:)
      • 你能解释一下不支持的设备吗?
      • 它将支持所有设备,toast仅适用于移动设备不支持裁剪意图的人。现在几乎所有设备都支持裁剪操作。
      • 好的,这个网址代表什么
      • 文件 f = new File(picUri); Uri contentUri = Uri.fromFile(f);我怎样才能得到这个?
      【解决方案4】:

      看看这个library。它提供基本的裁剪功能并被很多人使用

      【讨论】:

        【解决方案5】:

        看看this教程..

        【讨论】:

          猜你喜欢
          • 2014-02-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-11-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多