在Android中裁剪固定大小的图像

too*_*o42 15 android crop

我正在尝试裁剪图像,但我希望能够将裁剪区域设置为640px x 640px.我想阻止用户缩小到一个非常小的区域.所以基本上我宁愿为裁剪区域设置固定的高度和宽度.我已经调查了几个第三方库,但没有看到解决这个问题.我怎样才能做到这一点?

在此输入图像描述

kli*_*mat 17

我会使用以下解决方案之一:

  1. https://github.com/jdamcd/android-crop
  2. https://github.com/edmodo/cropper

两者似乎都适合解决您的问题,并确保涵盖更多边缘案例,设备和其他Android内容,以便更加稳定和可靠.

编辑:
我已经介绍了一些更改android-crop,现在您可以使用withFixedSize(int width, int height)以像素为单位设置固定裁剪区域.

看起来像这样:

 private void beginCrop(Uri source) {
        Uri outputUri = Uri.fromFile(new File(getCacheDir(), "cropped"));
        new Crop(source).output(outputUri).withFixedSize(640, 640).start(this);
    }
Run Code Online (Sandbox Code Playgroud)

这是拉取请求.

检查我的github上的完整代码https://github.com/mklimek/android-crop/tree/newfeature_fied_size_crop.

您可以克隆构建并在之后将其添加到项目中.

希望它会对你有所帮助.

  • @ toobsco42我编辑了我的答案,我认为它会解决你的问题. (3认同)

Ste*_*Bra 4

有一个方法可以使用\xc3\x86

\n\n
private void performCrop(){\n    try {\n        //call the standard crop action intent (the user device may not support it)\n        Intent cropIntent = new Intent("com.android.camera.action.CROP");\n        //indicate image type and Uri\n        cropIntent.setDataAndType(selectedImage, "image/*");\n        //set crop properties\n        cropIntent.putExtra("crop", "true");\n        //indicate aspect of desired crop\n        cropIntent.putExtra("aspectX", 1);\n        cropIntent.putExtra("aspectY", 1);\n        //indicate output X and Y\n        cropIntent.putExtra("outputX", 640);\n        cropIntent.putExtra("outputY", 640);\n        //retrieve data on return\n        cropIntent.putExtra("return-data", true);\n        //start the activity - we handle returning in onActivityResult\n        startActivityForResult(cropIntent, PIC_CROP);\n    }\n    catch(ActivityNotFoundException anfe){\n        //display an error message\n        String errorMessage = "Whoops - your device doesn\'t support the crop action!";\n        Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);\n        toast.show();\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

这部分代码是您\xc3\xb8感兴趣的:

\n\n
        cropIntent.putExtra("outputX", 640);\n        cropIntent.putExtra("outputY", 640);\n
Run Code Online (Sandbox Code Playgroud)\n\n

你应该像这样调用crop方法:

\n\n
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {  \n    if (requestCode == CAMERA && resultCode == RESULT_OK) {\n\n        selectedImage = data.getData();\n        performCrop();\n\n    } \n\n    if (requestCode == UPLOAD && resultCode == RESULT_OK) {\n        selectedImage = data.getData();\n        performCrop();\n    }\n\n    if (requestCode == PIC_CROP && resultCode == RESULT_OK){\n        Bundle extras = data.getExtras();\n        //get the cropped bitmap\n        Bitmap thePic = extras.getParcelable("data");\n\n        // Do what you want to do with the pic here\n    }\n\n\n\n}\n
Run Code Online (Sandbox Code Playgroud)\n