让用户裁剪图像(Let user crop image)

2019-07-20 15:12发布

我有在搞清楚如何让用户裁剪的图片很难。 我想给与加载的位图的位图变量设置为墙纸之前,裁剪图片。 但我不这样做......这里是我试过了。

第一个版本。 =按预期工作,但返回的图像是较差的分辨率。 输出更改为更高的值没有帮助。 正如我在一些后看到它是不推荐使用的相机,因为不是所有设备都支持这一点。

Intent intent = new Intent("com.android.camera.action.CROP");  
String path = Images.Media.insertImage(context.getContentResolver(), loaded,null, null);
Uri uri = Uri.parse(path);              
intent.setData(uri);  
intent.putExtra("crop", "true");  
intent.putExtra("aspectX", 1);  
intent.putExtra("aspectY", 1);  
intent.putExtra("outputX", 300);  
intent.putExtra("outputY", 300);  
intent.putExtra("noFaceDetection", true);  
intent.putExtra("return-data", true);                                  
startActivityForResult(intent, 2);

第二。 加载图像选择器,和作物之后。 我怎样才能configurate这直接我的图像上加载作物? 就在第1版喜欢

Intent photoPickerIntent = new Intent(MediaStore.ACTION_PICK);
photoPickerIntent.setData(uri);
photoPickerIntent.putExtra("crop", "true");
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(photoPickerIntent, 2);

和onActivity结果

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != RESULT_OK) { return; }
    if(requestCode == 2) {
        Bundle extras = data.getExtras();  
        if(extras != null ) {  
            Bitmap photo = extras.getParcelable("data");  
            loaded = photo;
        }
        WallpaperManager myWallpaperManager = WallpaperManager.getInstance(getApplicationContext());

        try {
            myWallpaperManager.setBitmap(loaded);
        } catch (IOException e) {}
    }
}

我不知道whever这些都是正确的方法,使这个工作,但我希望有人可以点我在正确的方向。 其中,为什么,以及如何使用。

更新:我仍然在等待有人指出,如何正确地做到这一点,下面的答案是工作,但返回较差的分辨率的图像,所以他们不使用选项

Answer 1:

好吧亲爱的在这里,我把我的裁切图像的整个代码在Android中。 这个全局变量。

    //This For Image Crop
        /**
         *  Uri for set image crop option .
         */
        private Uri mImageCaptureUri;
        /**
         *  int for set key and get key from result activity . 
         */
        public final int CROP_FROM_CAMERA = 0;

/**
     * Bitmap for apply Crop Operation Result.
     */
    private Bitmap _tempOpration;

    //This is Crop Method.

/**
     * Method for apply Crop .
     * @param filePath -  String path of file .
     */
    private void doCrop(String filePath){
        try{
            //New Flow
            mImageCaptureUri = Uri.fromFile(new File(filePath));

            final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
            Intent intent = new Intent("com.android.camera.action.CROP");
            intent.setType("image/*");
            List<ResolveInfo> list = getPackageManager().queryIntentActivities( intent, 0 );

            int size = list.size();
            if (size == 0) 
            {           
                Toast.makeText(this, "Can not find image crop app", Toast.LENGTH_SHORT).show();
                return;
            }
            else 
            {
                intent.setData(mImageCaptureUri);
                intent.putExtra("outputX", 300);
                intent.putExtra("outputY", 300);
                intent.putExtra("aspectX", 1);
                intent.putExtra("aspectY", 1);
                intent.putExtra("scale", true);
                intent.putExtra("return-data", true);

                if (size == 1) 
                {
                    Intent i = new Intent(intent);
                    ResolveInfo res = list.get(0);
                    i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
                    startActivityForResult(i, CROP_FROM_CAMERA);
                }

                else
                {
                    for (ResolveInfo res : list) 
                    {
                        final CropOption co = new CropOption();
                        co.title = getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
                        co.icon = getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
                        co.appIntent= new Intent(intent);
                        co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
                        cropOptions.add(co);
                    }

                    CropOptionAdapter adapter = new CropOptionAdapter(getApplicationContext(), cropOptions);
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("Choose Crop App");
                    builder.setAdapter( adapter, new DialogInterface.OnClickListener()
                    {
                        public void onClick( DialogInterface dialog, int item )
                        {
                            startActivityForResult( cropOptions.get(item).appIntent, CROP_FROM_CAMERA);
                        }
                    });

                    builder.setOnCancelListener( new DialogInterface.OnCancelListener() 
                    {
                        public void onCancel( DialogInterface dialog ) 
                        {
                            if (mImageCaptureUri != null ) 
                            {
                                getContentResolver().delete(mImageCaptureUri, null, null );
                                mImageCaptureUri = null;
                            }
                        }
                    } );
                    AlertDialog alert = builder.create();
                    alert.show();
                }
            }
        }
        catch (Exception ex) 
        {
            genHelper.showErrorLog("Error in Crop Function-->"+ex.toString());
        }
    }

这是另一类女巫使用了在应用程序来查找作物活动的意图。

CropOption类。

public class CropOption 
{
    public CharSequence title;
    public Drawable icon;
    public Intent appIntent;
}

这是使用对于显示列表中。

CropOptionAdapter

public class CropOptionAdapter extends ArrayAdapter<CropOption> 
{
    private ArrayList<CropOption> mOptions;
    private LayoutInflater mInflater;

    public CropOptionAdapter(Context context, ArrayList<CropOption> options) 
    {
        super(context, R.layout.crop_selector, options);

        mOptions    = options;

        mInflater   = LayoutInflater.from(context);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup group)
    {
        if (convertView == null)
            convertView = mInflater.inflate(R.layout.crop_selector, null);

        CropOption item = mOptions.get(position);

        if (item != null) {
            ((ImageView) convertView.findViewById(R.id.iv_icon)).setImageDrawable(item.icon);
            ((TextView) convertView.findViewById(R.id.tv_name)).setText(item.title);

            return convertView;
        }

        return null;
    }
}

布局文件CropOptionAdapter

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:gravity="center_vertical">

    <ImageView
        android:id="@+id/iv_icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <TextView
        android:id="@+id/tv_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""/>
</LinearLayout>

这是resultActivity.witch给裁剪图像。

/**
     * @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) return;
        switch (requestCode)
        {
        case CROP_FROM_CAMERA:
            if (data == null) 
            {
                genHelper.showToast("No Crop Activity in This");
                return;
            }
            final Bundle extras = data.getExtras();
            if (extras != null) 
            {
                try 
                {

                    _tempOpration=extras.getParcelable("data");
                    imageLayout.setImageBitmap(_tempOpration);
                    _tempOpration=null;

                } 
                catch (Exception e) 
                {
                    e.printStackTrace();
                }
            }
            break;
        }

    }

//做这类它的工作在我住的应用程序。

genHelper.showToast(“在此没有作物活动”);

我一般类,以帮助显示敬酒消息和错误日志。

最妙的运气。



Answer 2:

首先,变量:

final int PIC_CROP = 2;

Uri imageUri;
Bitmap thePic;

在你从你的相机或画廊PIC,把你的图像转换成一个URI(imageUri),用在这里称为“performCrop()”方法内部try / catch语句:

 private void performCrop(){
        try {
            Intent intent = new Intent("com.android.camera.action.CROP"); 
            intent.setType("image/*");

            List<ResolveInfo> list = getPackageManager().queryIntentActivities( intent, 0 );
            int size = list.size();

            if (size >= 0) {
                intent.setData(imageUri);        
                intent.putExtra("crop", "false");
                intent.putExtra("aspectX", 1);
                intent.putExtra("aspectY", 1);
                intent.putExtra("outputX", 256);
                intent.putExtra("outputY", 256);
                intent.putExtra("scale", true);  
                intent.putExtra("return-data", true);

                Intent i = new Intent(intent);
                ResolveInfo res = list.get(0);
                i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));

                startActivityForResult(i, PIC_CROP);  
            } 

        }
        catch(ActivityNotFoundException anfe){
            String errorMessage = "Whoops - your device doesn't support the crop action!";
            Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
            toast.show();
        }
    }

在方法onActivityResult:

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

        if(requestCode == PIC_CROP){

        if (resultCode == RESULT_OK) {
            Bundle extras = intent.getExtras();
            thePic = extras.getParcelable("data");
            imageViewPhoto.setImageBitmap(thePic); //in my case, set the image on screen

        }else{
            //do something
        }
    }
}


Answer 3:

由于类似的线程中提到,Android不具备正式的作物意图( https://commonsware.com/blog/2013/01/23/no-android-does-not-have-crop-intent.html ),所以我将使用“com.android.camera.action.CROP”望而却步。

然而,由于在这个问题最初发布时,Android已经在奇巧(19级),允许用户召唤作物这个形象和设置,如墙纸的活动增添了新的API。 见WallpaperManager.getCropAndSetWallpaperIntent(),这可能会解决您原来的问题。



Answer 4:

我用相机也有这个问题, ACTION_PICK ,尽管通过的决议是更大返回的图像是非常小的。 我得到了解决这个存储在一个临时文件导致作物图像

// temporary storage location, preferably in your cache directory
private final String tempFilePath = "somePath";

// URI instantiated with your temporary storage location
private Uri tempuri = Uri.fromFile(new File(tempFilePath));

// code for startActivityForResult
private final static int ACTIVITY_CROP_IMAGE = 1;

并呼吁这样的意图

Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra("crop", "true");
photoPickerIntent.putExtra("aspectX", wallpaperWidth);
photoPickerIntent.putExtra("aspectY", wallpaperHeight);
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempuri);
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(photoPickerIntent, ACTIVITY_CROP_IMAGE);

然后在onActivityResult

protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{
    if (resultCode != RESULT_OK) 
        return;

    if(requestCode == ACTIVITY_CROP_IMAGE) 
    {
        try 
        {
            Bitmap bmp = BitmapFactory.decodeFile(tempFilePath);
            if(bmp != null)
            {
                WallpaperManager myWallpaperManager = WallpaperManager.getInstance(getApplicationContext());
                myWallpaperManager.setBitmap(bmp);
            }
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
        finally
        {
            if(tempFilePath != null)
            {
                File tempFile = new File(tempFilePath);
                if(tempFile.exists())
                {
                    tempFile.delete();
                }
            }
        }
    }
}

我从我的头顶构造上面的代码,并没有实际编译任何一件事。 但基本是正确的,你应该得到的窍门;-)



文章来源: Let user crop image