当我改变相机的方向进行裁剪图像时,为啥我会丢失数据?

Posted

技术标签:

【中文标题】当我改变相机的方向进行裁剪图像时,为啥我会丢失数据?【英文标题】:Why did I lose data when I change the orientation of camera doing crop image?当我改变相机的方向进行裁剪图像时,为什么我会丢失数据? 【发布时间】:2014-12-15 12:52:36 【问题描述】:

我正在做一个应用程序,该应用程序从相机获取图像并在之后对其进行裁剪,但有些我如何丢失我的活动对象,当它回来时,我在它的 OnCreate 方法上得到 NullPointerExeception。但是当我从图库中选择图像时,它可以正常工作,因为它不会关闭活动。

public void onClick(DialogInterface dialog, int item) 
    if (items[item].equals("Camera")) 
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra("return-data", true);
        startActivityForResult(intent, Constants.PICK_FROM_CAMERA);
     else if (items[item].equals("Galeria")) 

        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        // ******** code for crop image
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 100);
        intent.putExtra("outputY", 100);
        intent.putExtra("max-height", 800);
        intent.putExtra("max-width", 800);
        intent.putExtra("return-data", true);
        intent.putExtra("scaleType", "centerCrop");
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        try 
             startActivityForResult(Intent.createChooser(intent,
             "Complete action using"), Constants.PICK_FROM_GALLERY);
         catch (ActivityNotFoundException e) 
        


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    super.onActivityResult(requestCode, resultCode, data);

    Bitmap tempImage;
    OutputStream fOut = null;

    File root = new File(Environment.getExternalStorageDirectory()
            + File.separator);

    try 
        File sdImageMainDirectory = new File(root, "foto.jpg");
        fOut = new FileOutputStream(sdImageMainDirectory);
     catch (Exception e) 
        e.printStackTrace();
    
    if (requestCode == Constants.PICK_FROM_CAMERA) 
        root = new File(Environment.getExternalStorageDirectory()
                + File.separator + "foto.jpg");
        Bitmap photo = (Bitmap) data.getExtras().get("data");
        saveBitmap(photo, Environment.getExternalStorageDirectory()
                + File.separator + "foto.jpg");
        try
            cropCapturedImage(Uri.fromFile(root));
        catch(ActivityNotFoundException aNFE)
            //display an error message if user device doesn't support
            String errorMessage = "Desculpe, seu dispositivo não suporta Crop!";
            Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
            toast.show();
        
    
    if (requestCode == Constants.PICK_FROM_GALLERY && data != null) 
        Bundle extras2 = data.getExtras();
        if (extras2 != null) 
            Bitmap photo = extras2.getParcelable("data");
            this.photo.setImageBitmap(photo);

            this.photo.buildDrawingCache();
            tempImage = this.photo.getDrawingCache();

            try 
                tempImage.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
                fOut.flush();
                fOut.close();
                BasicUserPerson.getInstance().setPhotoPath(
                        Environment.getExternalStorageDirectory()
                        + File.separator + "foto.jpg");
             catch (Exception e) 
                e.printStackTrace();
            
        
    

    //user is returning from cropping the image
    else if(requestCode == Constants.PIC_CROP && data != null)
        //get the returned data
        Bundle extras = data.getExtras();
        if (extras != null)

            Bitmap thePic = (Bitmap) data.getExtras().get("data");
            saveBitmap(thePic, Environment.getExternalStorageDirectory()
                    + File.separator + "foto.jpg");

            photo.setImageBitmap(thePic);
            BasicUserPerson.getInstance().setPhotoPath(
                    Environment.getExternalStorageDirectory()
                    + File.separator + "foto.jpg");
        
    


public void saveBitmap(Bitmap photo, String path) 
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    photo.compress(Bitmap.CompressFormat.JPEG, 100, bytes);

    File f = new File(path);
    try 
        f.createNewFile();
        FileOutputStream fo = new FileOutputStream(f);
        fo.write(bytes.toByteArray());
        fo.close();
     catch (IOException e) 
        e.printStackTrace();
    


public void cropCapturedImage(Uri picUri)
    Intent cropIntent = new Intent("com.android.camera.action.CROP");
    cropIntent.setDataAndType(picUri, "image/*");
    cropIntent.putExtra("crop", "true");
    cropIntent.putExtra("aspectX", 1);
    cropIntent.putExtra("aspectY", 1);
    cropIntent.putExtra("outputX", 256);
    cropIntent.putExtra("outputY", 256);
    cropIntent.putExtra("return-data", true);
    cropIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
    startActivityForResult(cropIntent, Constants.PIC_CROP);


@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);

    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.dados_pessoais);

    fullName = (EditText) findViewById(R.id.edtFullName);
    cpf = (EditText) findViewById(R.id.edtCpf);
    email = (EditText) findViewById(R.id.edtDadEmail);
    ddd = (EditText) findViewById(R.id.edtDadDDD);
    telefone = (EditText) findViewById(R.id.edtDadTele);
    ddd2 = (EditText) findViewById(R.id.edtDadDDD2);
    celular = (EditText) findViewById(R.id.edtDadTel);
    btSalvar = (ImageView) findViewById(R.id.imgSalvar);
    head = (ImageView) findViewById(R.id.imgDadosHead);
    sexo = (Spinner) findViewById(R.id.spnSex);
    birthday = (EditText) findViewById(R.id.edtBrithday);
    civil = (Spinner) findViewById(R.id.spnCivil);
    loadingCity = (ImageView) findViewById(R.id.imgLoadingCity);
    escolaridade = (Spinner) findViewById(R.id.spnEscolaridade);
    cep = (EditText) findViewById(R.id.edtCep);
    state = (Spinner) findViewById(R.id.spnState);
    city = (Spinner) findViewById(R.id.spnCity);
    endereco = (EditText) findViewById(R.id.edtEndereco);
    bairro = (EditText) findViewById(R.id.edtBairro);
    num = (EditText) findViewById(R.id.edtNum);
    comp = (EditText) findViewById(R.id.edtComp);
    photo = (ImageView) findViewById(R.id.imgPhoto);

    btSalvar.setOnClickListener(this);
    photo.setOnClickListener(this);

    //Line of error
    if (!User.getInstance().getFullName().equals("null") && !User.getInstance().getFullName().equals(""))
        fullName.setText(User.getInstance().getFullName());
    
    if (!BasicUserPerson.getInstance().getPersonRegistration().equals("null") && !BasicUserPerson.getInstance().getPersonRegistration().equals(""))
        cpf.setText(BasicUserPerson.getInstance().getPersonRegistration());
    
    if (!User.getInstance().getEmail().equals("null") && !User.getInstance().getEmail().equals("null"))
        email.setText(User.getInstance().getEmail());
    
    email.setKeyListener(null);
    if (!BasicUserPerson.getInstance().getMobilePhone().equals("null") && !BasicUserPerson.getInstance().getMobilePhone().equals(""))
        String tel = BasicUserPerson.getInstance().getMobilePhone().replace("(", "").replace(")", "").replace(" ", "");
        ddd.setText(tel.subSequence(0, 2));
        celular.setText(tel.substring(2));
    
    if (!BasicUserPerson.getInstance().getPhone().equals("null") && !BasicUserPerson.getInstance().getPhone().equals(""))
        String tel = BasicUserPerson.getInstance().getPhone().replace("(", "").replace(")", "").replace(" ", "");
        ddd2.setText(tel.subSequence(0, 2));
        telefone.setText(tel.substring(2));
    
    if (!BasicUserPerson.getInstance().getBirthday().equals("null") && !BasicUserPerson.getInstance().getBirthday().equals(""))
        birthday.setText(BasicUserPerson.getInstance().getBirthday());
    
    if (!BasicUser.getInstance().locationObj.getZipCode().equals("null") && !BasicUser.getInstance().locationObj.getZipCode().equals(""))
        cep.setText(BasicUser.getInstance().locationObj.getZipCode());         
    
    if (!BasicUser.getInstance().locationObj.getAddress().equals("null") && !BasicUser.getInstance().locationObj.getAddress().equals(""))
        endereco.setText(BasicUser.getInstance().locationObj.getAddress());         
    
    if (!BasicUser.getInstance().locationObj.getNeighborhood().equals("null") && !BasicUser.getInstance().locationObj.getNeighborhood().equals(""))
        bairro.setText(BasicUser.getInstance().locationObj.getNeighborhood());         
    


它输出:

  12-15 21:22:55.002: E/AndroidRuntime(2263): FATAL EXCEPTION: main
    12-15 21:22:55.002: E/AndroidRuntime(2263): Process: br.com.inradar, PID: 2263
    12-15 21:22:55.002: E/AndroidRuntime(2263): java.lang.RuntimeException: Unable to start activity ComponentInfobr.com.inradar/br.com.inradar.activities.DadosPessoais: java.lang.NullPointerException
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2202)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2252)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.app.ActivityThread.access$800(ActivityThread.java:139)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1200)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.os.Handler.dispatchMessage(Handler.java:102)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.os.Looper.loop(Looper.java:136)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.app.ActivityThread.main(ActivityThread.java:5103)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at java.lang.reflect.Method.invokeNative(Native Method)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at java.lang.reflect.Method.invoke(Method.java:515)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:606)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at dalvik.system.NativeStart.main(Native Method)
    12-15 21:22:55.002: E/AndroidRuntime(2263): Caused by: java.lang.NullPointerException
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at br.com.inradar.activities.DadosPessoais.onCreate(DadosPessoais.java:176)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.app.Activity.performCreate(Activity.java:5275)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2166)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     ... 11 more

【问题讨论】:

如果你需要一些帮助,你应该分享一些代码 发生这种情况是因为我们的 onFinish() 正在调用。 如果NPE发生在onCreate方法中,请问你贴一下这个方法和一些日志吗? 我指出了错误发生的地方 【参考方案1】:

你是这样用的吗

    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
if(requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) 
    if(resultCode == RESULT_OK) 
          // stub here
          
        
       

【讨论】:

我试过了,但还是一样,错误是在那部分之后 你能准确指出异常是在哪一行抛出的吗? 我发现了问题here

以上是关于当我改变相机的方向进行裁剪图像时,为啥我会丢失数据?的主要内容,如果未能解决你的问题,请参考以下文章

从 Swift 中的自定义相机拍摄后裁剪图像

即时裁剪图像

如何处理IOS图像裁剪中的图像旋转问题

Android 自定义相机 - 在矩形内裁剪图像

为啥我会从“double”转换为“float”,可能会丢失数据警告?(c)

方向改变时相机出现问题