0

我正在做一个相机应用程序,使用我在互联网上找到的代码来捕获和裁剪图像。直到我想将图像保存在 SDd 卡中之前它都做得很好。它意外停止并产生以下错误:

08-06 15:06:58.341: E/AndroidRuntime(26462): FATAL EXCEPTION: main

08-06 15:06:58.341: E/AndroidRuntime(26462): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=2, result=-1, data=Intent { (has extras) }} to activity {net.londatiga.android/net.londatiga.android.MainActivity}: java.lang.NullPointerException

08-06 15:06:58.341: E/AndroidRuntime(26462):    at android.app.ActivityThread.deliverResults(ActivityThread.java:2994)

08-06 15:06:58.341: E/AndroidRuntime(26462):    at android.app.ActivityThread.handleSendResult(ActivityThread.java:3037)

08-06 15:06:58.341: E/AndroidRuntime(26462):    at android.app.ActivityThread.access$1100(ActivityThread.java:128)

08-06 15:06:58.341: E/AndroidRuntime(26462):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1191)

08-06 15:06:58.341: E/AndroidRuntime(26462):    at android.os.Handler.dispatchMessage(Handler.java:99)

08-06 15:06:58.341: E/AndroidRuntime(26462):    at android.os.Looper.loop(Looper.java:137)

08-06 15:06:58.341: E/AndroidRuntime(26462):    at android.app.ActivityThread.main(ActivityThread.java:4514)

08-06 15:06:58.341: E/AndroidRuntime(26462):    at java.lang.reflect.Method.invokeNative(Native Method)

08-06 15:06:58.341: E/AndroidRuntime(26462):    at java.lang.reflect.Method.invoke(Method.java:511)

08-06 15:06:58.341: E/AndroidRuntime(26462):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993)

08-06 15:06:58.341: E/AndroidRuntime(26462):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760)

08-06 15:06:58.341: E/AndroidRuntime(26462):    at dalvik.system.NativeStart.main(Native Method)

08-06 15:06:58.341: E/AndroidRuntime(26462): Caused by: java.lang.NullPointerException

08-06 15:06:58.341: E/AndroidRuntime(26462):    at java.io.File.fixSlashes(File.java:185)

08-06 15:06:58.341: E/AndroidRuntime(26462):    at java.io.File.<init>(File.java:134)

08-06 15:06:58.341: E/AndroidRuntime(26462):    at net.londatiga.android.MainActivity.saveBitmapToFile(MainActivity.java:128)

08-06 15:06:58.341: E/AndroidRuntime(26462):    at net.londatiga.android.MainActivity.onActivityResult(MainActivity.java:112)

08-06 15:06:58.341: E/AndroidRuntime(26462):    at android.app.Activity.dispatchActivityResult(Activity.java:4746)

08-06 15:06:58.341: E/AndroidRuntime(26462):    at android.app.ActivityThread.deliverResults(ActivityThread.java:2990)

08-06 15:06:58.341: E/AndroidRuntime(26462):    ... 11 more

编码:

package net.londatiga.android;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Path;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {
    private Uri mImageCaptureUri;
    private ImageView mImageView;
    private String path;
    private Bitmap bitmap;

    private static final int PICK_FROM_CAMERA = 1;
    private static final int CROP_FROM_CAMERA = 2;
    private static final int PICK_FROM_FILE = 3;


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

        setContentView(R.layout.main);

        final String [] items           = new String [] {"Take from camera", "Select from gallery"};                
        ArrayAdapter<String> adapter    = new ArrayAdapter<String> (this, android.R.layout.select_dialog_item,items);
        AlertDialog.Builder builder     = new AlertDialog.Builder(this);

        builder.setTitle("Select Image");
        builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
            public void onClick( DialogInterface dialog, int item ) { //pick from camera
                if (item == 0) {
                    Intent intent    = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                    mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                                       "tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));

                    intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);

                    try {
                        intent.putExtra("return-data", true);

                        startActivityForResult(intent, PICK_FROM_CAMERA);
                    } catch (ActivityNotFoundException e) {
                        e.printStackTrace();
                    }
                } else { //pick from file
                    Intent intent = new Intent();

                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);

                    startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
                }
            }
        } );

        final AlertDialog dialog = builder.create();

        Button button   = (Button) findViewById(R.id.btn_crop);
        mImageView      = (ImageView) findViewById(R.id.iv_photo);

        button.setOnClickListener(new View.OnClickListener() {  
            public void onClick(View v) {
                dialog.show();
            }
        });
    }

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

        switch (requestCode) {
            case PICK_FROM_CAMERA:
                doCrop();

                break;

            case PICK_FROM_FILE: 
                mImageCaptureUri = data.getData();

                doCrop();

                break;          

            case CROP_FROM_CAMERA:          
                Bundle extras = data.getExtras();

                if (extras != null) {               
                    Bitmap photo = extras.getParcelable("data");
                    saveBitmapToFile("/sdcard/cropped_img.jpg", photo);

                    mImageView.setImageBitmap(photo);
                }

                File f = new File(mImageCaptureUri.getPath());            

                if (f.exists()) f.delete();

                break;
//
        }
    }

    private boolean saveBitmapToFile(String string, Bitmap photo) {

        File file = new File(path);
        boolean res = false; if (!file.exists())
        {
        try 
        {
        FileOutputStream fos = new FileOutputStream(file); 
        res = bitmap.compress(CompressFormat.JPEG, 100, fos); fos.close();
        } catch (Exception e) 
        {   }
        } return res;
        }

//  }

    private void doCrop() {
        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", 200);
            intent.putExtra("outputY", 200);
            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();
            }
        }
    }
}
4

1 回答 1

0

你得到 NPE 。看到这一行 bitmap.compress(CompressFormat.JPEG, 100, fos); fos.close(); . 是分配了 y 值的位图变量。我没有在你的代码中看到它。instread 尝试 photo..compress(CompressFormat.JPEG, 100, fos);

您的代码中有很多错误。上面提到的是一个。

我刚刚看到您在 File file = new File(path); 处遇到异常 此变量路径未定义。用你的路径值初始化它。

于 2012-08-06T08:14:46.383 回答