在位图上获得致命的异常

时间:2013-06-05 00:57:11

标签: android bitmap android-imageview bitmapimage bitmapdata

在使用移动相机拍摄图像后尝试使用ImageView绘制图像时,我得到了致命的异常。但是我在使用Bitmap创建图像时遇到异常。

代码::

   public class MMS extends Activity implements OnClickListener {
    int TAKE_PHOTO_CODE = 0;
    public static int count=0;
    EditText preLoc,comeby;
Button ok,capture;
String photo;
String dir;

boolean GPS,flag;
String cityName=null; 
String SubThorugh = null;
Intent i;
ImageView iv;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mms);

    preLoc = (EditText)findViewById(R.id.etPreLoc1);
    comeby = (EditText)findViewById(R.id.etComing1);
    iv = (ImageView)findViewById(R.id.ImageView1);
    //ok = (Button)findViewById(R.id.bOK1);
    capture = (Button) findViewById(R.id.btnCapture);
    capture.setOnClickListener(this);

}
@Override
public void onClick(View arg0) {
    // TODO Auto-generated method stub
    switch(arg0.getId())
    {
    case R.id.btnCapture:
        capturePicture();
        break;

    }
}




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

    if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
        Log.d("CameraDemo", "Pic saved");
        Toast.makeText(getApplicationContext(), "photo saved as: "+photo, Toast.LENGTH_LONG).show();
        Bitmap photo = (Bitmap) data.getExtras().get("data");
        iv.setImageBitmap(photo);
    }
}
private void capturePicture() {

    //here,we are making a folder named picFolder to store pics taken by the camera using this application
    final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/"; 
    File newdir = new File(dir); 
    newdir.mkdirs();
 // here,counter will be incremented each time,and the picture taken by camera will be stored as 1.jpg,2.jpg and likewise.
    count++;
    String file = dir+count+".jpg";
    photo = file;
    File newfile = new File(file);
    try {
        newfile.createNewFile();
    } catch (IOException e) {}       

    Uri outputFileUri = Uri.fromFile(newfile);

    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);

    startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);

}

}

和例外是:

06-04 22:15:46.515: W/dalvikvm(22711): threadid=1: thread exiting with uncaught exception (group=0x40018578)
06-04 22:15:46.546: E/AndroidRuntime(22711): FATAL EXCEPTION: main
06-04 22:15:46.546: E/AndroidRuntime(22711): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=null} to activity {com.example.nirbhaya/com.example.nirbhaya.MMS}: java.lang.NullPointerException
06-04 22:15:46.546: E/AndroidRuntime(22711):    at android.app.ActivityThread.deliverResults(ActivityThread.java:2536)
06-04 22:15:46.546: E/AndroidRuntime(22711):    at android.app.ActivityThread.handleSendResult(ActivityThread.java:2578)
06-04 22:15:46.546: E/AndroidRuntime(22711):    at android.app.ActivityThread.access$2000(ActivityThread.java:117)
06-04 22:15:46.546: E/AndroidRuntime(22711):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:965)
06-04 22:15:46.546: E/AndroidRuntime(22711):    at android.os.Handler.dispatchMessage(Handler.java:99)
06-04 22:15:46.546: E/AndroidRuntime(22711):    at android.os.Looper.loop(Looper.java:130)
06-04 22:15:46.546: E/AndroidRuntime(22711):    at android.app.ActivityThread.main(ActivityThread.java:3687)
06-04 22:15:46.546: E/AndroidRuntime(22711):    at java.lang.reflect.Method.invokeNative(Native Method)
06-04 22:15:46.546: E/AndroidRuntime(22711):    at java.lang.reflect.Method.invoke(Method.java:507)
06-04 22:15:46.546: E/AndroidRuntime(22711):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
06-04 22:15:46.546: E/AndroidRuntime(22711):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
06-04 22:15:46.546: E/AndroidRuntime(22711):    at dalvik.system.NativeStart.main(Native Method)
06-04 22:15:46.546: E/AndroidRuntime(22711): Caused by: java.lang.NullPointerException
06-04 22:15:46.546: E/AndroidRuntime(22711):    at com.example.nirbhaya.MMS.onActivityResult(MMS.java:125)
06-04 22:15:46.546: E/AndroidRuntime(22711):    at android.app.Activity.dispatchActivityResult(Activity.java:3908)
06-04 22:15:46.546: E/AndroidRuntime(22711):    at android.app.ActivityThread.deliverResults(ActivityThread.java:2532)
06-04 22:15:46.546: E/AndroidRuntime(22711):    ... 11 more
06-04 22:15:46.921: D/dalvikvm(22711): GC_CONCURRENT freed 268K, 48% free 2956K/5639K, external 583K/945K, paused 3ms+4ms
  
    第125行的

代码是     位图照片=(位图)data.getExtras()。get(“data”);

  

2 个答案:

答案 0 :(得分:0)

引用MediaStore documentation

  

调用者可以传递额外的EXTRA_OUTPUT来控制该图像的写入位置。如果EXTRA_OUTPUT不存在,则在额外字段中返回小尺寸图像作为Bitmap对象。这对于只需要小图像的应用程序非常有用。如果存在EXTRA_OUTPUT,则将将全尺寸图像写入EXTRA_OUTPUT的Uri值。

这意味着如果你设置了EXTRA_OUTPUT参数,它就不会在额外字段中返回一个Bitmap对象 - 它只会将全尺寸图像写入指定的Uri。

答案 1 :(得分:0)

我同意詹姆斯的答案是正确的,因此您必须直接从存储它的路径中选择图像,路径将是

String path = newfile.getAbsolutePath(); 然后你可以使用这个函数从该路径创建位图,该函数将path作为参数并返回位图。

public Bitmap getImage1(String path) throws IOException
    {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        int srcWidth = options.outWidth;
        int srcHeight = options.outHeight;
        int[] newWH =  new int[2];
        newWH[0] = srcWidth/2;
        newWH[1] = (newWH[0]*srcHeight)/srcWidth;

        int inSampleSize = 1;
        while(srcWidth / 2 >= newWH[0]){
            srcWidth /= 2;
            srcHeight /= 2;
            inSampleSize *= 2;
        }

         options.inJustDecodeBounds = false;
        options.inDither = false;
        options.inSampleSize = inSampleSize;
        options.inScaled = false;
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        Bitmap sampledSrcBitmap = BitmapFactory.decodeFile(path,options);
        ExifInterface exif = new ExifInterface(path);
        String s=exif.getAttribute(ExifInterface.TAG_ORIENTATION);
        System.out.println("Orientation>>>>>>>>>>>>>>>>>>>>"+s);
        Matrix matrix = new Matrix();
        float rotation = rotationForImage(con, Uri.fromFile(new File(path)));
        if (rotation != 0f) {
            matrix.preRotate(rotation);
        }

        Bitmap pqr=Bitmap.createBitmap(
                sampledSrcBitmap, 0, 0, sampledSrcBitmap.getWidth(), sampledSrcBitmap.getHeight(), matrix, true);


        return pqr;
    }   


    public  float rotationForImage(Context context, Uri uri) {
        if (uri.getScheme().equals("content")) {
            String[] projection = { Images.ImageColumns.ORIENTATION };
            Cursor c = context.getContentResolver().query(
                    uri, projection, null, null, null);
            if (c.moveToFirst()) {
                return c.getInt(0);
            }
        } else if (uri.getScheme().equals("file")) {
            try {
                ExifInterface exif = new ExifInterface(uri.getPath());
                int rotation = (int)exifOrientationToDegrees(
                        exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                                ExifInterface.ORIENTATION_NORMAL));
                return rotation;
            } catch (IOException e) {
                e.printStackTrace();
            }catch (Exception e) {
                e.printStackTrace();
             }

        }
        return 0f;
    }

    private static float exifOrientationToDegrees(int exifOrientation) {
        if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) {
            return 90;
        } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {
            return 180;
        } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) {
            return 270;
        }
        return 0;
    }
}

其他功能用于为图像提供正确的方向。