Byron Kiourtzoglou

About Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.

HTTP Camera live preview example

With this example we are going to demonstrate how to create Live Camera preview in Android. The Android SDK includes a Camera class that is used to set image capture settings, start/stop preview, snap pictures, and retrieve frames for encoding for video. It is a handy abstraction of the real hardware device

What we are essentially going to do is setup a web camera to publish static images in a predefined URL and then grab these images from our application and present them as motion pictures
 
 
 
 
In short, to create live camera previews you should:

as shown in the code snippets below:

package com.javacodegeeks.android.camera;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;

public class HttpCamera {

    private static final int CONNECT_TIMEOUT = 1000;
    private static final int SOCKET_TIMEOUT = 1000;

    private final String url;
    private final Rect bounds;
    private final boolean preserveAspectRatio;
    private final Paint paint = new Paint();

    public HttpCamera(String url, int width, int height, boolean preserveAspectRatio) {

  this.url = url;

  bounds = new Rect(0, 0, width, height);

  this.preserveAspectRatio = preserveAspectRatio;

  paint.setFilterBitmap(true);

  paint.setAntiAlias(true);
    }

    private Bitmap retrieveBitmap() throws IOException {

  Bitmap bitmap = null;

  InputStream in = null;

  int response = -1;

  try {

URL url = new URL(this.url);

HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();

httpConn.setConnectTimeout(CONNECT_TIMEOUT);

httpConn.setReadTimeout(SOCKET_TIMEOUT);

httpConn.setRequestMethod("GET");

httpConn.connect();

response = httpConn.getResponseCode();

if (response == HttpURLConnection.HTTP_OK) {

    in = httpConn.getInputStream();

    bitmap = BitmapFactory.decodeStream(in);

}

return bitmap;

  } 

  catch (Exception e) {

return null;

  }

  finally {

if (in != null) try {

    in.close();

} catch (IOException e) {

    /* ignore */

}

  }

    }

    public boolean captureAndDraw(Canvas canvas) throws IOException {

  Bitmap bitmap = retrieveBitmap();

  if (bitmap == null) throw new IOException("Response Code: ");

  //render it to canvas, scaling if necessary

  if (bounds.right == bitmap.getWidth() && bounds.bottom == bitmap.getHeight()) {

canvas.drawBitmap(bitmap, 0, 0, null);

  } else {

Rect dest;

if (preserveAspectRatio) {

    dest = new Rect(bounds);

    dest.bottom = bitmap.getHeight() * bounds.right / bitmap.getWidth();

    dest.offset(0, (bounds.bottom - dest.bottom)/2);

} 

else {

    dest = bounds;

}

canvas.drawBitmap(bitmap, null, dest, paint);

  }

  return true;

    }

}
package com.javacodegeeks.android.camera;

import android.content.Context;
import android.graphics.Canvas;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class HttpCameraPreview extends SurfaceView implements SurfaceHolder.Callback {

    private static final String url = "http://10.0.2.2:8080";

    private CanvasThread canvasThread;

    private SurfaceHolder holder;
    private HttpCamera camera;

    private int viewWidth;
    private int viewHeight;

    public HttpCameraPreview(Context context, int viewWidth, int viewHeight) {

  super(context);

  holder = getHolder();

  holder.addCallback(this);

  holder.setType(SurfaceHolder.SURFACE_TYPE_NORMAL);

  this.viewWidth = viewWidth;

  this.viewHeight = viewHeight;

  canvasThread = new CanvasThread();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder2, int format, int w, int h) {

  try {

Canvas c = holder.lockCanvas(null);

camera.captureAndDraw(c);

if (c != null) {

    holder.unlockCanvasAndPost(c);

}

  } 

  catch (Exception e) {

Log.e(getClass().getSimpleName(), "Error when surface changed", e);

camera = null;

  }
    }

    @Override
    public void surfaceCreated(SurfaceHolder arg0) {

  try {

camera = new HttpCamera(url, viewWidth, viewHeight, true);

canvasThread.setRunning(true);

canvasThread.start();

  } 

  catch (Exception e) {

Log.e(getClass().getSimpleName(), "Error while creating surface", e);

camera = null;

  }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder arg0) {

  camera = null;

  boolean retry = true;

  canvasThread.setRunning(false);

  while (retry) {

try {

    canvasThread.join();

    retry = false;

} catch (InterruptedException e) {

}

  }

    }

    private class CanvasThread extends Thread {

  private boolean running;

  public void setRunning(boolean running){

this.running = running;

  }

  public void run() {

     while (running) {

   Canvas c = null;

   try {

 c = holder.lockCanvas(null);

 synchronized (holder) {

     camera.captureAndDraw(c);

 }

   }

   catch (Exception e) {

 Log.e(getClass().getSimpleName(), "Error while drawing canvas", e);

   }

   finally {

 if (c != null) {

     holder.unlockCanvasAndPost(c);

 }

   }

     }

  }

    }

}
package com.javacodegeeks.android.camera;

import android.app.Activity;
import android.os.Bundle;
import android.view.Display;
import android.view.SurfaceView;
import android.view.Window;

public class MyCamAppActivity extends Activity {

    private int viewWidth;
    private int viewHeight;

    private SurfaceView cameraPreview;

    private static final boolean useHttpCamera = true;

    @Override
    public void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  requestWindowFeature(Window.FEATURE_NO_TITLE);

  calculateDisplayDimensions();

  if (useHttpCamera) {

cameraPreview = new HttpCameraPreview(this, viewWidth, viewHeight);

  }

  else {

cameraPreview = new CameraPreview(this);

  }

  setContentView(cameraPreview);

    }

    private void calculateDisplayDimensions() {

  Display display = getWindowManager().getDefaultDisplay();

  viewWidth = display.getWidth();

  viewHeight = display.getHeight();
    }    

}
<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.javacodegeeks.android.camera"

android:versionCode="1"

android:versionName="1.0">

    <application android:icon="@drawable/icon" android:label="@string/app_name">

  <activity android:name=".MyCamAppActivity"

android:label="@string/app_name">

<intent-filter>

    <action android:name="android.intent.action.MAIN" />

    <category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

  </activity>   
    </application>

    <uses-sdk android:minSdkVersion="3" />

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

</manifest>

 
This was an example of how to create Live Camera previews in Android.

Related Article:

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....

Examples Java Code Geeks and all content copyright © 2010-2015, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

Get ready to Rock!
To download the books, please verify your email address by following the instructions found on the email we just sent you.

THANK YOU!

Close