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:

Related Whitepaper:

Beginning Android Application Development (Free Sample Chapter)

Create must-have applications for the latest Android OS!

The Android OS is a popular and flexible platform for many of today's most in-demand mobile devices. This full-color guide offers you a hands-on introduction to creating Android applications for the latest mobile devices. Veteran author Wei Meng Lee accompanies each lesson with real-world examples to drive home the content he covers. Beginning with an overview of core Android features and tools, he moves at a steady pace while teaching everything you need to know to successfully develop your own Android applications.

Get it Now!  

Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
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.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books