Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/201.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
android KitKat图像裁剪_Android_Android Intent_Android 4.4 Kitkat_Android Camera Intent - Fatal编程技术网

android KitKat图像裁剪

android KitKat图像裁剪,android,android-intent,android-4.4-kitkat,android-camera-intent,Android,Android Intent,Android 4.4 Kitkat,Android Camera Intent,我正在将图像url传递给以下方法 private void performCrop(Uri imageUri){ try { Intent intent = new Intent("com.android.camera.action.CROP"); // intent.setType("image/*"); intent.setDataAndType(imageUri, "image/*");

我正在将图像url传递给以下方法

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

这段代码对我来说很成功。试试看

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();
    }
}
private static final int-CAMERA_REQUEST=1;
公共静态最终int媒体类型图像=1;
最终int PIC_裁剪=12;
按钮btnCamera;
ImageView iv;
乌里·皮库里;
静态文件mediaFile,sendFile;
setOnClickListener(新的OnClickListener(){
@凌驾
公共void onClick(视图v){
//TODO自动生成的方法存根
onImgProfile();
}
});
void onImgProfile(){
Intent captureIntent=新的意图(MediaStore.ACTION\u IMAGE\u CAPTURE);
picUri=getOutputMediaFileUri(媒体类型图像);
putExtra(MediaStore.EXTRA_输出,picUri);
startActivityForResult(捕获意图、摄像头请求);
}
私有Uri getOutputMediaFileUri(int类型){
返回Uri.fromFile(getOutputMediaFile(类型));
}
私有文件getOutputMediaFile(int类型){
File mediaStorageDir=新文件(
getExternalStorageDirectory(),“MyCameraApp”);
如果(!mediaStorageDir.exists()){
如果(!mediaStorageDir.mkdirs()){
Log.d(“MyCameraApp”,“创建目录失败”);
返回null;
}
}
//创建媒体文件名
字符串时间戳=新的SimpleDataFormat(“yyyyMMdd_HHmmss”)
.格式(新日期());
如果(类型==媒体类型图像){
mediaFile=新文件(mediaStorageDir.getPath()+File.separator
+“IMG_”+时间戳+”.jpg”);
}否则{
返回null;
}
返回媒体文件;
}
@抑制警告(“未选中”)
@凌驾
ActivityResult上的公共void(int请求代码、int结果代码、意图数据){
//TODO自动生成的方法存根
super.onActivityResult(请求代码、结果代码、数据);
if(requestCode==CAMERA\u请求){
//如果(Build.VERSION.SDK_INT<19){
试一试{
if(mediaFile.exists()){
performCrop();
//新建SavePhotoData().execute();
}
}捕获(例外e){
//TODO:处理异常
}
// }
}else if(requestCode==11){
试一试{
picUri=data.getData();
Log.i(“uri”,即“+picUri”);
performCrop();
}捕获(例外e){
//TODO:处理异常
}
}else if(requestCode==PIC_裁剪){
//获取返回的数据
试一试{
Bundle extras=data.getExtras();
//获取裁剪后的位图
位图thePic=extras.getParcelable(“数据”);
//检索对ImageView的引用
//显示返回的裁剪图像
iv.设置图像位图(thePic);
File mediaStorageDir=新文件(
Environment.getExternalStorageDirectory(),
“MyCameraApp”);
如果(!mediaStorageDir.exists()){
如果(!mediaStorageDir.mkdirs()){
Log.d(“MyCameraApp”,“创建目录失败”);
}
}
//创建媒体文件名
字符串时间戳=新的SimpleDataFormat(“yyyyMMdd_HHmmss”)
.格式(新日期());
sendFile=新文件(mediaStorageDir.getPath()+File.separator
+“IMG_”+时间戳+”.png”);
FileOutputStream fOut=新的FileOutputStream(sendFile);
thePic.compress(Bitmap.CompressFormat.PNG,85,fOut);
fOut.flush();
fOut.close();
}捕获(例外e){
e、 printStackTrace();
}
}
如果(结果代码==3){
Bundle b=data.getExtras();
b、 获取字符串(“msg”);
}
};
私有无效performCrop(){
//注意例外情况
试一试{
//调用标准裁剪操作意图(用户设备可能不支持
//(支持它)
试一试{
Intent-cropIntent=newintent(“com.android.camera.action.CROP”);
//指示图像类型和Uri
setDataAndType(picUri,“image/*”);
//设置作物属性
cropIntent.putExtra(“作物”、“真实”);
//表示所需作物的外观
cropIntent.putExtra(“aspectX”,1);
cropIntent.putExtra(“aspectY”,1);
//指示输出X和Y
cropIntent.putExtra(“输出”,256);
cropIntent.putExtra(“outputY”,256);
//返回时检索数据
cropIntent.putExtra(“返回数据”,真);
//启动活动-我们在onActivityResult中处理返回
startActivityForResult(cropIntent、PIC_作物);
}捕获(例外e){
//TODO:处理异常
}
}
//响应设备不支持裁剪操作的用户
捕获(ActivityNotFoundException anfe){
//显示错误消息
String errorMessage=“哇-您的设备不支持裁剪操作!”;
Toast Toast=Toast.makeText(getApplicationContext(),errorMessage,
烤面包片(长/短);
toast.show();
}
}

此代码不仅适用于kitkat,而且适用于所有android版本

根据@commonware,android所有设备都没有裁剪意图

所以更好的方法是使用库

其中包括:


是否有onActivityResult(…)函数?如果是,请发布它,如果不是,那可能是你的问题是的,我有,可能这个问题只发生在nexus 7(android 4.4)上如果你在ActivityResult上调试(…),你看到数据是吗!=null?它不进入onActivityResult()。。。这就是问题所在Android没有
裁剪
意图
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();
    }
}