I would like to crop image directly from the Camera Preview using a Rectangle.I get the following error in my LogCat when the following code is used:
skia(24596): onFlyCompress
AndroidRuntime(24596): FATAL EXCEPTION: main
AndroidRuntime(24596): java.lang.NullPointerException
AndroidRuntime(24596): at com.example.mycameraapp.CameraActivity.getBoundData(CameraActivity.java:417)
AndroidRuntime(24596): at com.example.mycameraapp.CameraActivity$2.onPreviewFrame(CameraActivity.java:320)
AndroidRuntime(24596): at android.hardware.Camera$EventHandler.handleMessage(Camera.java:791)
AndroidRuntime(24596): at android.os.Handler.dispatchMessage(Handler.java:99)
AndroidRuntime(24596): at android.os.Looper.loop(Looper.java:137)
AndroidRuntime(24596): at android.app.ActivityThread.main(ActivityThread.java:5103)
AndroidRuntime(24596): at java.lang.reflect.Method.invokeNative(Native Method)
AndroidRuntime(24596): at java.lang.reflect.Method.invoke(Method.java:525)
AndroidRuntime(24596): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
AndroidRuntime(24596): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
AndroidRuntime(24596): at dalvik.system.NativeStart.main(Native Method)
My code generates error in the method getBoundData
presumably when I use YuvImage
and compressToJpeg
methods.The code of the methods is here:
ByteArrayOutputStream bos;
public byte[] getBoundData(final byte[] data,final Rect rect)
{
/*int h=mCamera.getParameters().getPictureSize().height;
int w=mCamera.getParameters().getPictureSize().width;
int bitsPerPixel=ImageFormat.getBitsPerPixel(mCamera.getParameters().getPictureFormat());
int bufferSize=w*h*(bitsPerPixel/8);
byte[] out=new byte[bufferSize];*/
new Thread()
{
public void run()
{
final int h=mCamera.getParameters().getPreviewSize().height;
final int w=mCamera.getParameters().getPreviewSize().width;
YuvImage yuvImage=new YuvImage(data,ImageFormat.NV21,w,h,null);
bos=new ByteArrayOutputStream();
yuvImage.compressToJpeg(rect, 100, bos);
}
}.start();
//Log.d(TAG,"Bound Array Size: "+bos.size());
return bos.toByteArray();
}
This method is called within the PreviewCallback like this:
PreviewCallback mPreviewCallback=new PreviewCallback() {
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
// TODO Auto-generated method stub
byte[] boxData=null;
Rect rect=mBox.getRect();
if(rect!=null)
boxData=getBoundData(data,rect);
else
boxData=data;
//file saving code...previously tested.
This is called in using mCamera.setPreviewCallback(mPreviewCallback);
within the doSnap
method.
What causes this error and how do I rectify it? Also,is this the best way of cropping Image directly from the CameraPreview in Android.
return bos.toByteArray();
You bos
is null
here. It is only initialized in a background thread later.
If you need to communicate data back from a background thread, use e.g. a callback interface. AsyncTask
makes background thread task handling much simpler BTW.