Android的奇巧图像裁剪

Android的奇巧图像裁剪

本文介绍了Android的奇巧图像裁剪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我传递图片的URL以下方法

 私人无效performCrop(URI imageUri){
        尝试 {
            意向意图=新的意图(com.android.camera.action.CROP);
          // intent.setType(图像/ *);
            intent.setDataAndType(imageUri,图像/ *);
            名单< ResolveInfo> 。表= getActivity()getPackageManager()queryIntentActivities(意向,0);
            INT大小=则为list.size();

            如果(大小与GT; = 0){
                intent.setData(imageUri);
                intent.putExtra(裁剪,真);
                intent.putExtra(aspectX,0);
                intent.putExtra(aspectY,0);
                intent.putExtra(outputX,150);
                intent.putExtra(outputY,150);
                intent.putExtra(规模化,真正的);
                intent.putExtra(scaleUpIfNeeded,真正的);
                intent.putExtra(回归数据,真正的);
                意图I =新的意向(意向);

                ResolveInfo解析度= list.get(0);

                i.setComponent(新的组件名(res.activityInfo.packageName,res.activityInfo.name));
                的System.out.println(startActivityForResult之前);
                尝试{
                startActivityForResult(1,2);
                }赶上(例外五){
                    e.printStackTrace();
                }
             }

        }
        赶上(ActivityNotFoundException anfe){
            字符串的errorMessage =哎呦 - 您的设备不支持作物的行动!
            //吐司面包= Toast.makeText(这一点,的errorMessage,Toast.LENGTH_SHORT);
            //toast.show();
        }
    }
 

一些图片被裁剪,但一些图像都没有。当我裁剪图像,然后我的应用程序的活动被关闭,应用程序启动时的previous或发射活动,这样有什么问题?

主要的问题是我没有收到在日志中的猫任何警告或错误,当我调试它的钱柜的System.out.println(startActivityForResult之前);该方案excutes,这意味着它不进去或致电onActivityResult()。

下面是onActivityResult方法

  @覆盖
   公共无效onActivityResult(INT申请code,INT结果code,意图数据){
      // TODO自动生成方法存根
      super.onActivityResult(要求code,因此code,数据);




如果(要求code == 2及和放大器;结果code == getActivity()RESULT_OK){
            的System.out.println(内部逻辑......);
            尝试{
                如果(数据!= NULL){

               //获取返回的数据
                    捆绑额外= data.getExtras();
                    //获取裁剪位图
                    BMP位= extras.getParcelable(数据);

                        imageView.setImageBitmap(BMP);


                }
            }赶上(例外五){
                e.printStackTrace();
            }

     }
    }
 

解决方案

这code成功的作品me.try它

 私有静态最终诠释CAMERA_REQUEST = 1;
公共静态最终诠释MEDIA_TYPE_IMAGE = 1;
最终诠释PIC_CROP = 12;
按钮btnCamera;
ImageView的IV;
乌里picUri;
静态文件媒体文件,发送文件;



btnCamera.setOnClickListener(新OnClickListener(){

        @覆盖
        公共无效的onClick(视图v){
            // TODO自动生成方法存根

            onImgProfile();
        }
    });



无效onImgProfile(){
    意图captureIntent =新的意图(MediaStore.ACTION_IM​​AGE_CAPTURE);

    picUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

    captureIntent.putExtra(MediaStore.EXTRA_OUTPUT,picUri);

    startActivityForResult(captureIntent,CAMERA_REQUEST);
}


私人乌里getOutputMediaFileUri(整型){
    返回Uri.fromFile(getOutputMediaFile(类型));
}

私人文件getOutputMediaFile(整型){

    文件mediaStorageDir =新的文件(
            Environment.getExternalStorageDirectory(),MyCameraApp);

    如果(!mediaStorageDir.exists()){
        如果(!mediaStorageDir.mkdirs()){
            Log.d(MyCameraApp,无法创建目录);
            返回null;
        }
    }

    //创建一个媒体文件名
    字符串的timeStamp =新的SimpleDateFormat(YYYYMMDD_HHMMSS)
            .format(新日期());

    如果(类型== MEDIA_TYPE_IMAGE){
        媒体文件=新的文件(mediaStorageDir.getPath()+文件分割符
                +IMG_+的timeStamp +.JPG);
    } 其他 {
        返回null;
    }

    返回媒体文件;
}



    @燮pressWarnings(未登记)
@覆盖
公共无效onActivityResult(INT申请code,INT结果code,意图数据){
    // TODO自动生成方法存根
    super.onActivityResult(要求code,因此code,数据);

    如果(要求code == CAMERA_REQUEST){
        //如果(Build.VERSION.SDK_INT所述19){
        尝试 {
            如果(mediaFile.exists()){
                performCrop();
                //新SavePhotoData()执行()。
            }

        }赶上(例外五){
            // TODO:处理异常

        }
        //}

    }否则,如果(要求code == 11){

        尝试 {
            picUri = data.getData();
            Log.i(URI,+ picUri);
            performCrop();
        }赶上(例外五){
            // TODO:处理异常

        }

    }否则,如果(要求code == PIC_CROP){
        //获取返回的数据

        尝试 {
            捆绑额外= data.getExtras();

            //获取裁剪位图
            位图thePic = extras.getParcelable(数据);
            //检索引用的ImageView

            //显示返回裁剪图像
            iv.setImageBitmap(thePic);

            文件mediaStorageDir =新的文件(
                    Environment.getExternalStorageDirectory(),
                    MyCameraApp);

            如果(!mediaStorageDir.exists()){
                如果(!mediaStorageDir.mkdirs()){
                    Log.d(MyCameraApp,无法创建目录);

                }
            }

            //创建一个媒体文件名
            字符串的timeStamp =新的SimpleDateFormat(YYYYMMDD_HHMMSS)
                    .format(新日期());

            SENDFILE =新的文件(mediaStorageDir.getPath()+文件分割符
                    +IMG_+的timeStamp +巴纽);

            FileOutputStream中FOUT =新的FileOutputStream(发送文件);

            thePic.com preSS(Bitmap.Com pressFormat.PNG,85,FOUT);
            fOut.flush();
            fOut.close();

        }赶上(例外五){
            e.printStackTrace();

        }
    }

    如果(结果code == 3){
        叠B = data.getExtras();
        b.getString(味精);
    }
};



私人无效performCrop(){
    //照顾例外
    尝试 {
        //调用标准作物动作意图(用户设备可能不
        //支持它)
        尝试 {
            意图cropIntent =新的意向书(com.android.camera.action.CROP);
            //显示的图像类型和URI
            cropIntent.setDataAndType(picUri,图像/ *);
            //设置裁剪属性
            cropIntent.putExtra(裁剪,真);
            //注明所需作物方面
            cropIntent.putExtra(aspectX,1);
            cropIntent.putExtra(aspectY,1);
            //指示输出X和Y
            cropIntent.putExtra(outputX,256);
            cropIntent.putExtra(outputY,256);
            //检索返回数据
            cropIntent.putExtra(回归数据,真正的);
            //启动活动 - 我们办理回国onActivityResult
            startActivityForResult(cropIntent,PIC_CROP);
        }赶上(例外五){
            // TODO:处理异常
        }
    }
    //响应用户的设备不支持的作物采取行动
    赶上(ActivityNotFoundException anfe){
        //显示错误消息
        字符串的errorMessage =哎呦 - 您的设备不支持作物的行动!
        吐司面包= Toast.makeText(getApplicationContext()的errorMessage,
                Toast.LENGTH_SHORT);
        toast.show();
    }
}
 

这code工作不仅奇巧,但Android的所有cersion

I am passing image url to the following method

private void performCrop(Uri imageUri){
        try {
            Intent intent = new Intent("com.android.camera.action.CROP");
          //  intent.setType("image/*");
            intent.setDataAndType(imageUri, "image/*");
            List<ResolveInfo> list = getActivity().getPackageManager().queryIntentActivities( intent, 0 );
            int size = list.size();

            if (size >= 0) {
                intent.setData(imageUri);
                intent.putExtra("crop", "true");
                intent.putExtra("aspectX", 0);
                intent.putExtra("aspectY", 0);
                intent.putExtra("outputX", 150);
                intent.putExtra("outputY", 150);
                intent.putExtra("scale", true);
                intent.putExtra("scaleUpIfNeeded", 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));
                System.out.println("before startActivityForResult");
                try{
                startActivityForResult(i, 2);
                }catch(Exception e){
                    e.printStackTrace();
                }
             }

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

some of images are cropped but some image are not. When I crop image then my app's activity is closed and application starts it's previous or launcher activity so what is the problem??

the main issue is I am not getting any warning or error in log cat, and when I debug it the the till "System.out.println("before startActivityForResult");" the program excutes, that means it does not goes in or calling onActivityResult().

here is onActivityResult method

 @Override
   public void onActivityResult(int requestCode, int resultCode, Intent data) {
      // TODO Auto-generated method stub
      super.onActivityResult(requestCode, resultCode, data);




if(requestCode ==2 && resultCode == getActivity().RESULT_OK){
            System.out.println("inside logic...");
            try{
                if (data != null) {

               //  get the returned data
                    Bundle extras = data.getExtras();
                    // get the cropped bitmap
                    Bitmap bmp = extras.getParcelable("data");

                        imageView.setImageBitmap(bmp);


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

     }
    }
解决方案

this code works successfully for me.try it

private static final int CAMERA_REQUEST = 1;
public static final int MEDIA_TYPE_IMAGE = 1;
final int PIC_CROP = 12;
Button btnCamera;
ImageView iv;
Uri picUri;
static File mediaFile, sendFile;



btnCamera.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            onImgProfile();
        }
    });



void onImgProfile() {
    Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    picUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

    captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, picUri);

    startActivityForResult(captureIntent, CAMERA_REQUEST);
}


private Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
}

private File getOutputMediaFile(int type) {

    File mediaStorageDir = new File(
            Environment.getExternalStorageDirectory(), "MyCameraApp");

    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d("MyCameraApp", "failed to create directory");
            return null;
        }
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
            .format(new Date());

    if (type == MEDIA_TYPE_IMAGE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + ".jpg");
    } else {
        return null;
    }

    return mediaFile;
}



    @SuppressWarnings("unchecked")
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == CAMERA_REQUEST) {
        // if (Build.VERSION.SDK_INT < 19) {
        try {
            if (mediaFile.exists()) {
                performCrop();
                // new SavePhotoData().execute();
            }

        } catch (Exception e) {
            // TODO: handle exception

        }
        // }

    } else if (requestCode == 11) {

        try {
            picUri = data.getData();
            Log.i("uri", "" + picUri);
            performCrop();
        } catch (Exception e) {
            // TODO: handle exception

        }

    } else if (requestCode == PIC_CROP) {
        // get the returned data

        try {
            Bundle extras = data.getExtras();

            // get the cropped bitmap
            Bitmap thePic = extras.getParcelable("data");
            // retrieve a reference to the ImageView

            // display the returned cropped image
            iv.setImageBitmap(thePic);

            File mediaStorageDir = new File(
                    Environment.getExternalStorageDirectory(),
                    "MyCameraApp");

            if (!mediaStorageDir.exists()) {
                if (!mediaStorageDir.mkdirs()) {
                    Log.d("MyCameraApp", "failed to create directory");

                }
            }

            // Create a media file name
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                    .format(new Date());

            sendFile = new File(mediaStorageDir.getPath() + File.separator
                    + "IMG_" + timeStamp + ".png");

            FileOutputStream fOut = new FileOutputStream(sendFile);

            thePic.compress(Bitmap.CompressFormat.PNG, 85, fOut);
            fOut.flush();
            fOut.close();

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

        }
    }

    if (resultCode == 3) {
        Bundle b = data.getExtras();
        b.getString("msg");
    }
};



private void performCrop() {
    // take care of exceptions
    try {
        // call the standard crop action intent (the user device may not
        // support it)
        try {
            Intent cropIntent = new Intent("com.android.camera.action.CROP");
            // indicate image type and Uri
            cropIntent.setDataAndType(picUri, "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", 256);
            cropIntent.putExtra("outputY", 256);
            // retrieve data on return
            cropIntent.putExtra("return-data", true);
            // start the activity - we handle returning in onActivityResult
            startActivityForResult(cropIntent, PIC_CROP);
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
    // respond to users whose devices do not support the crop action
    catch (ActivityNotFoundException anfe) {
        // display an error message
        String errorMessage = "Whoops - your device doesn't support the crop action!";
        Toast toast = Toast.makeText(getApplicationContext(), errorMessage,
                Toast.LENGTH_SHORT);
        toast.show();
    }
}

this code works for not only kitkat but all cersion of android

这篇关于Android的奇巧图像裁剪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 17:41