Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/wcf/4.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 如何解决图像捕获数据错误?_Android_Android Camera_Android Camera Intent - Fatal编程技术网

Android 如何解决图像捕获数据错误?

Android 如何解决图像捕获数据错误?,android,android-camera,android-camera-intent,Android,Android Camera,Android Camera Intent,我有这个代码来捕获图像或选择从画廊,然后裁剪它。图像不显示,并且在ActivityResult中数据变量为空。我该怎么解决这个问题?请帮忙 提前谢谢 import java.io.File; import java.io.FileOutputStream; import android.annotation.SuppressLint; import android.app.Activity; import android.content.ActivityNotFoundException; i

我有这个代码来捕获图像或选择从画廊,然后裁剪它。图像不显示,并且在ActivityResult中数据变量为空。我该怎么解决这个问题?请帮忙

提前谢谢

import java.io.File;
import java.io.FileOutputStream;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.kbeanie.imagechooser.api.ChooserType;
import com.kbeanie.imagechooser.api.ChosenImage;
import com.kbeanie.imagechooser.api.ImageChooserListener;
import com.kbeanie.imagechooser.api.ImageChooserManager;

public class ProfileName extends Activity implements TextWatcher,
        OnClickListener, ImageChooserListener {
    int choice;
    private static int RESULT_CAPTURE = 1;
    private static int RESULT_LOAD_IMAGE = 2;
    ImageView click;
    ImageView cam;
    boolean cond = false;
    EditText nameText;
    TextView name_view;
    ImageView camImage;
    String Name = null;
    String fileName;
    ImageView exist;
    ImageView save;
    Bitmap bm;
    int currentState = 0;
    ImageView btnForward, btnBack;
    RelativeLayout rl_name, rl_profile_create, rl_display;
    private ImageChooserManager imageChooserManager;
    private int chooserType;
    private String filePath;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.profile_name);
        cam = (ImageView) findViewById(R.id.camera);
        nameText = (EditText) findViewById(R.id.editText1);
        nameText.addTextChangedListener(this);
        btnForward = (ImageView) findViewById(R.id.btnForward);
        btnForward.setOnClickListener(this);
        btnBack = (ImageView) findViewById(R.id.btnBack);
        btnBack.setOnClickListener(this);
        save = (ImageView) findViewById(R.id.save);
        save.setOnClickListener(this);
        name_view = (TextView) findViewById(R.id.textView2);
        camImage = (ImageView) findViewById(R.id.camImage);

        exist = (ImageView) findViewById(R.id.existing_img);
        exist.setOnClickListener(this);
        click = (ImageView) findViewById(R.id.new_img);
        click.setOnClickListener(this);

        rl_name = (RelativeLayout) findViewById(R.id.rl_name);
        rl_profile_create = (RelativeLayout) findViewById(R.id.rl_profile_create);
        rl_display = (RelativeLayout) findViewById(R.id.rl_display);

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        // TODO Auto-generated method stub

    }

    @Override
    public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub
        Name = nameText.getText().toString();
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.btnForward:
            // if (Name != null) {
            //
            // Intent j = new Intent(ProfileName.this, CreateProfile.class);
            // j.putExtra("name", nameText.getText().toString());
            // j.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
            // | Intent.FLAG_ACTIVITY_NEW_TASK);
            // startActivity(j);

            // finish();
            // } else {
            // Toast.makeText(ProfileName.this, "Please Enter The Name",
            // Toast.LENGTH_SHORT).show();
            // }
            if (currentState < 3) {
                currentState++;
            }
            displayScreens();
            break;
        case R.id.btnBack:

            if (currentState != 0) {
                currentState--;
            }
            displayScreens();

            break;
        case R.id.save:

            if (Name != null) {
                save(bm);
                Intent j = new Intent(ProfileName.this, MainActivity.class);
                j.putExtra("bit", bm);
                j.putExtra("name", Name);
                j.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                        | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(j);
                SharedPreferences settings = getSharedPreferences(
                        Start.PREFS_NAME, 0);
                SharedPreferences.Editor editor = settings.edit();
                editor.putBoolean("hasLoggedIn", true);
                editor.commit();
                finish();
            } else {
                Toast.makeText(ProfileName.this, "Please Enter The Name",
                        Toast.LENGTH_SHORT).show();
            }

            break;
        case R.id.existing_img:

            Intent i = new Intent(
                    Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            choice = 2;
            startActivityForResult(i, RESULT_LOAD_IMAGE);

            break;
        case R.id.new_img:

            // open();

            chooserType = ChooserType.REQUEST_CAPTURE_PICTURE;
            imageChooserManager = new ImageChooserManager(this,
                    ChooserType.REQUEST_CAPTURE_PICTURE, "myfolder", true);
            imageChooserManager.setImageChooserListener(this);
            try {
                filePath = imageChooserManager.choose();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }

            break;

        default:
            break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // TODO Auto-generated method stub
        if (requestCode == RESULT_CAPTURE && resultCode == RESULT_OK
        /* && null != data */&& choice == 1) {

            File file = new File(Environment.getExternalStorageDirectory()
                    + File.separator + "img.jpg");
            // Crop the captured image using an other intent
            try {
                /* the user's device may not support cropping */
                cropCapturedImage(Uri.fromFile(file));
            } catch (ActivityNotFoundException aNFE) {
                // display an error message if user device doesn't support
                String errorMessage = "Sorry - your device doesn't support the crop action!";
                Toast toast = Toast.makeText(this, errorMessage,
                        Toast.LENGTH_SHORT);
                toast.show();
            }
            // Bitmap bp = (Bitmap) data.getExtras().get("data");
            // // save(bp);
            // bm=bp;
            // cam.setImageBitmap(bp);
        } else if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
                && null != data && choice == 2) {
            Uri selectedImage = data.getData();
            try {
                /* the user's device may not support cropping */
                cropCapturedImage(selectedImage);
            } catch (ActivityNotFoundException aNFE) {
                // display an error message if user device doesn't support
                String errorMessage = "Sorry - your device doesn't support the crop action!";
                Toast toast = Toast.makeText(this, errorMessage,
                        Toast.LENGTH_SHORT);
                toast.show();
            }
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            String picturePath = cursor.getString(cursor
                    .getColumnIndex(filePathColumn[0]));
            cursor.close();
            // save(BitmapFactory.decodeFile(picturePath));
            bm = BitmapFactory.decodeFile(picturePath);
            // bm=ilu.decodeBitmapFromPath(picturePath);
            cam.setImageBitmap(BitmapFactory.decodeFile(picturePath));

        }
        if (requestCode == 3 && data != null) {
            // Create an instance of bundle and get the returned data
            Bundle extras = data.getExtras();
            // get the cropped bitmap from extras
            Bitmap thePic = extras.getParcelable("data");
            // set image bitmap to image view
            cam.setImageBitmap(thePic);
            bm = thePic;
        } else if (resultCode == RESULT_OK
                && (requestCode == ChooserType.REQUEST_PICK_PICTURE || requestCode == ChooserType.REQUEST_CAPTURE_PICTURE)) {
            if (imageChooserManager == null) {
                reinitializeImageChooser();
            }
            imageChooserManager.submit(requestCode, data);
        }
    }

    private void reinitializeImageChooser() {
        imageChooserManager = new ImageChooserManager(this, chooserType,
                "myfolder", true);
        imageChooserManager.setImageChooserListener(this);
        imageChooserManager.reinitialize(filePath);
    }

    public void open() {
        // Intent intent = new
        // Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        // startActivityForResult(intent,REQUEST_IMAGE_CAPTURE);
        // choice=1;
        Intent intent = new Intent(
                android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        /* create instance of File with name img.jpg */
        File file = new File(Environment.getExternalStorageDirectory()
                + File.separator + "img1.jpg");
        /* put uri as extra in intent object */

        if (!file.exists()) {
            file.mkdirs();
        } else {
            file.delete();
            file.mkdirs();
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        /* start activity for result pass intent as argument and request code */
        // startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);

        try {

            startActivityForResult(intent, RESULT_CAPTURE);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }

        choice = 1;
    }

    @SuppressLint("SdCardPath")
    public void save(Bitmap bitM) {
        // fileName=nameText.getText().toString()+".jpg";
        fileName = Name;
        File direct = new File(Environment.getExternalStorageDirectory()
                .getAbsoluteFile() + "/FabFamily/Me");

        if (!direct.exists()) {
            direct = new File(Environment.getExternalStorageDirectory()
                    .getAbsoluteFile() + "/FabFamily/Me");
            direct.mkdirs();
        } else if (direct.exists()) {
            direct.delete();
            direct = new File(Environment.getExternalStorageDirectory()
                    .getAbsoluteFile() + "/FabFamily/Me");
            direct.mkdirs();
        }

        File file = new File(new File(Environment.getExternalStorageDirectory()
                .getAbsoluteFile() + "/FabFamily/Me"), fileName + ".jpg");
        if (file.exists()) {
            file.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(file);
            bitM.compress(Bitmap.CompressFormat.JPEG, 75, out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void displayScreens() {
        switch (currentState) {
        case 0:

            rl_name.setVisibility(View.VISIBLE);
            rl_profile_create.setVisibility(View.GONE);
            rl_display.setVisibility(View.GONE);
            save.setVisibility(View.GONE);
            btnBack.setVisibility(View.GONE);
            btnBack.setVisibility(View.VISIBLE);

            break;
        case 1:

            rl_name.setVisibility(View.GONE);
            rl_profile_create.setVisibility(View.VISIBLE);
            rl_display.setVisibility(View.GONE);
            btnBack.setVisibility(View.VISIBLE);
            btnForward.setVisibility(View.VISIBLE);
            save.setVisibility(View.GONE);

            break;
        case 2:

            rl_name.setVisibility(View.GONE);
            rl_profile_create.setVisibility(View.GONE);
            rl_display.setVisibility(View.VISIBLE);
            btnForward.setVisibility(View.GONE);
            btnBack.setVisibility(View.VISIBLE);
            save.setVisibility(View.VISIBLE);
            camImage.setImageBitmap(bm);
            name_view.setText(Name);

            break;

        default:
            break;
        }
    }

    public void cropCapturedImage(Uri picUri) {
        // call the standard crop action intent
        Intent cropIntent = new Intent("com.android.camera.action.CROP");
        // indicate image type and Uri of image
        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, 3);
    }

    @Override
    public void onImageChosen(com.kbeanie.imagechooser.api.ChosenImage image) {
        // TODO Auto-generated method stub
        if (image != null) {
            try {
                // Bitmap photo = BitmapFactory.decodeFile(image
                // .getFilePathOriginal());
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 8;
                // Bitmap preview_bitmap=BitmapFactory.decodeFile(image,

                Bitmap photo = BitmapFactory.decodeFile(
                        image.getFilePathOriginal(), options);

                try {
                    ExifInterface exif = new ExifInterface(
                            image.getFilePathOriginal());
                    int orientation = exif.getAttributeInt(
                            ExifInterface.TAG_ORIENTATION, 1);
                    // Log.d("EXIF", "Exif: " + orientation);
                    Matrix matrix = new Matrix();
                    if (orientation == 6) {
                        matrix.postRotate(90);
                    } else if (orientation == 3) {
                        matrix.postRotate(180);
                    } else if (orientation == 8) {
                        matrix.postRotate(270);
                    }

                    photo = Bitmap.createBitmap(photo, 0, 0, photo.getWidth(),
                            photo.getHeight(), matrix, true); // rotating bitmap

                    // if (orientation != 0) {
                    // photo = getResizedBitmap(photo, 180, 360);
                    // }

                } catch (Exception e) {

                }
                // if (photo.getWidth() > 180 && photo.getHeight() >
                // 250) {
                // photo = getResizedBitmap(photo, 180, 250);
                // }
                // imgVw.setImageBitmap(photo);

                // txtImgPath.setText(image.getFilePathOriginal());
                Log.i("sdfh", "IMAGEPATH :" + image.getFilePathOriginal());
                //
                // base64 = Utility.BitMapToString(photo);
                // imgPathLayout.setVisibility(View.VISIBLE);

            } catch (Exception e) {
                Log.i("", "dsvj on image chosen:" + e.getMessage());
            }
        }
    }

    @Override
    public void onError(String reason) {
        // TODO Auto-generated method stub

    }
}
导入java.io.File;
导入java.io.FileOutputStream;
导入android.annotation.SuppressLint;
导入android.app.Activity;
导入android.content.ActivityNotFoundException;
导入android.content.Intent;
导入android.content.SharedReferences;
导入android.database.Cursor;
导入android.graphics.Bitmap;
导入android.graphics.BitmapFactory;
导入android.graphics.Matrix;
导入android.media.ExifInterface;
导入android.net.Uri;
导入android.os.Bundle;
导入android.os.Environment;
导入android.provider.MediaStore;
导入android.text.Editable;
导入android.text.TextWatcher;
导入android.util.Log;
导入android.view.view;
导入android.view.view.OnClickListener;
导入android.widget.EditText;
导入android.widget.ImageView;
导入android.widget.RelativeLayout;
导入android.widget.TextView;
导入android.widget.Toast;
导入com.kbeanie.imagechooser.api.ChooserType;
导入com.kbeanie.imagechooser.api.ChosenImage;
导入com.kbeanie.imagechooser.api.ImageChooserListener;
导入com.kbeanie.imagechooser.api.ImageChooserManager;
公共类ProfileName扩展活动实现TextWatcher,
OnClickListener,ImageChooserListener{
智力选择;
私有静态int-RESULT_-CAPTURE=1;
私有静态int结果\加载\图像=2;
图像视图点击;
图像视图凸轮;
布尔cond=false;
编辑文本名称文本;
TextView名称\u视图;
图像视图;
字符串名称=null;
字符串文件名;
图像视图存在;
图像视图保存;
位图bm;
int currentState=0;
图像视图BTN前进,BTN后退;
RelativeLayout rl_名称、rl_配置文件创建、rl_显示;
专用图像选择器管理器图像选择器管理器;
私有int选择器类型;
私有字符串文件路径;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_name);
cam=(图像视图)findViewById(R.id.camera);
nameText=(EditText)findViewById(R.id.editText1);
nameText.addTextChangedListener(此);
btnForward=(ImageView)findViewById(R.id.btnForward);
btnForward.setOnClickListener(此);
btnBack=(ImageView)findViewById(R.id.btnBack);
btnBack.setOnClickListener(这个);
save=(ImageView)findviewbyd(R.id.save);
save.setOnClickListener(这个);
name_view=(TextView)findViewById(R.id.textView2);
camImage=(ImageView)findViewById(R.id.camImage);
exist=(ImageView)findViewById(R.id.existing\u img);
exist.setOnClickListener(this);
单击=(ImageView)findViewById(R.id.new\u img);
单击.setOnClickListener(此);
rl_name=(RelativeLayout)findviewbyd(R.id.rl_name);
rl_profile_create=(RelativeLayout)findViewById(R.id.rl_profile_create);
rl_display=(RelativeLayout)findviewbyd(R.id.rl_display);
}
@凌驾
更改前的公共无效(字符序列、整数开始、整数计数、,
整数后){
//TODO自动生成的方法存根
}
@凌驾
public void onTextChanged(字符序列、int start、int before、int count){
//TODO自动生成的方法存根
}
@凌驾
公共无效后文本已更改(可编辑){
//TODO自动生成的方法存根
Name=nameText.getText().toString();
}
@凌驾
公共void onClick(视图v){
//TODO自动生成的方法存根
开关(v.getId()){
案例R.id.btnForward:
//if(Name!=null){
//
//Intent j=新的Intent(ProfileName.this,CreateProfile.class);
//j.putExtra(“name”,nameText.getText().toString());
//j.addFlags(Intent.FLAG\u活动\u清除\u顶部
//|意图。标记活动(新任务);
//星触觉(j);
//完成();
//}其他{
//Toast.makeText(ProfileName.this,“请输入名称”,
//吐司。长度(短)。show();
// }
如果(当前状态<3){
currentState++;
}
显示屏();
打破
案例R.id.btnBack:
如果(当前状态!=0){
当前状态--;
}
显示屏();
打破
案例R.id.save:
if(Name!=null){
保存(bm);
Intent j=新的Intent(ProfileName.this,MainActivity.class);
j、 putExtra(“位”,bm);
j、 putExtra(“名称”,名称);
j、 添加标志(Intent.FLAG\u活动\u清除\u顶部
|意图。标记活动(新任务);
星触觉(j);
SharedReferences设置=GetSharedReferences(
Start.PREFS_名称,0);
SharedReferences.Editor=settings.edit();
putBoolean(“hasLoggedIn”,true);
commit();
完成();
}否则{
Toast.makeText(ProfileName.this,“请输入名称”,
吐司。长度(短)。show();
}
打破
案例R.id.existing\u img:
意向i=新意向(
意向、行动、选择,
android.provider.MediaStore.Images.Media.EXTERNAL\u CONTENT\u URI);
选择=2;
startActivityForResult(i,结果加载图像);
打破
案例R.id.new\u img:
//open();
chooserType=chooserType.REQUEST\u CAPTURE\u PICTURE;
imageChooserManager=新建imageChooserManager(此,
选择type.REQUEST\u CAPTURE\P