Search code examples
javaandroidbitmapfactorypreviewcallback

Save PreviewFrame as JPEG on external storage (Android)


I am trying to save the preview frames from the camera on the external storage of my device.

These are the permissions in my Manifest:

<uses-permission android:name="android.permission.CAMERA" />
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

And this is the Callback inside the surfaceChanged():

  mCamera.setPreviewCallback(new PreviewCallback() {

                public void onPreviewFrame(byte[] data, Camera camera) {
                    Camera.Parameters parameters = camera.getParameters();
                  Size size = camera.getParameters().getPreviewSize();
                  frames++;
                  Log.v("Framecount", "Frame: " + frames + "Größe: " + data.length);

                  int width = parameters.getPreviewSize().width;
                  int height = parameters.getPreviewSize().height;

                  ByteArrayOutputStream outstr = new ByteArrayOutputStream();
                  Rect rect = new Rect(0, 0, width, height); 
                  YuvImage yuvimage=new YuvImage(data,ImageFormat.NV21,width,height,null);
                  yuvimage.compressToJpeg(rect, 100, outstr);
                  Bitmap bmp = BitmapFactory.decodeByteArray(outstr.toByteArray(), 0, outstr.size());
                  Bitmap thumbnail = Bitmap.createScaledBitmap(bmp, 20, 20, false);
                try   {
                    File sdCard = Environment.getExternalStorageDirectory();
                    File dir = new File (sdCard.getAbsolutePath() + "/.aaaaaaaaa/");
                    dir.mkdirs();
                    File file = new File(dir, "filename.jpg");
                    FileOutputStream output = new FileOutputStream(file);
                  yuvimage.compressToJpeg(rect, 90, output);
                  output.flush();
                  output.close();
                }
                catch(Exception e) {
                    Log.v("Error", "Error");
                }



                }
              });

Showing the Preview frames on the screen is not the problem, I just can't save them. Does anyone have an idea what could be wrong?


Solution

  • If you want your jpg's immediately visible in the Gallery then invoke the media scanner on every new file. Search for the two lines of code on this site.