Search code examples
androidcameramjpegnanohttpd

camera picture streaming as mjpeg with nanohttpd in android


I have created an app and using nanohttpd I could get info from the phone. I could open camera in the background and took the picture. But I cannot stream it as motion jpeg through nanohttpd.

I have searched the answer on the Internet, but unfortunately, I could not reach any success. I have found many ways and open source projects(ipweb-cam, spydroid), but they didn't help me.

Please, help me.


Solution

  • For those who are interested in the answer, and need some code, here:

    cameraObject.setPreviewCallback(new Camera.PreviewCallback(){
         @Override
         public void onPreviewFrame(byte[] data, Camera camera) {
    
                try {
    
                    if (cameraObject.getParameters().getPreviewFormat() == ImageFormat.NV21) {
                        timestampBeforecompression = SystemClock.uptimeMillis();
                        yuvImage = new YuvImage(data, imageFormat, width, height, null);
                        yuvImage.compressToJpeg(rect, 75, mByteArrayOutputStream);
    
                        frameToStream = mByteArrayOutputStream.toByteArray();
    
                        bitmap = BitmapFactory.decodeByteArray(frameToStream, 0, frameToStream.length);
                        mByteArrayOutputStream.reset();
                        bitmap = Bitmap.createScaledBitmap(bitmap, 320, 240, true);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 60, mByteArrayOutputStream);
                        frameToStream = null;
                        frameToStream = mByteArrayOutputStream.toByteArray();
    
                        compressionMillis = SystemClock.uptimeMillis() - timestampBeforecompression;
                        if (125 - compressionMillis > 0) {
                            SystemClock.sleep(125 - compressionMillis);
                        }
    
                        if (mJpegStream != null) {
                            mJpegStream.streamJpeg(frameToStream, frameToStream.length, Long.MIN_VALUE);
                        }
    
                        if (mByteArrayOutputStream != null) {
                            mByteArrayOutputStream.reset();
                        }
    
                        frameToStream = null;
                   }
    
               } catch (Exception e) {
                    System.out.println("Oops: " + e.getMessage());
               }
    
          }
    });
    

    Note that you can omit compressionMillis and System.sleep(). I used them to control frame rate, if you have any misunderstanding feel free to write.