Java – convert byte array to image (jpeg)

I am working on getting a jpeg camera (OV2640) working with my CTS module and stream live video over serial port.

I tried using PROCESSING to receive the files the display them real-time on-screen, however, it seems is not possible. I thought is faster this way then write an application using Java. I was wrong :)

I tried to look online for an easy way to do it: receive a jpeg file as a binary stream over a serial connection then display it in real-time on the PC.

The binary data streaming was already working, so I needed to write a piece of code to handle the rest: receive the data and put it in an array:

if (len > 0) {
  for (int i = 0; i < len; i++) {
    if ((inBuffCounter == 0) && (i == 0)){
      // check for 'J' - start of data transfer
      if (serBuffer[i] != 0x4a){
    // store data in the array unless EOI is received
    else if (!((serBuffer[i] == 0xd9) && (serBuffer[i-1] == 0xff))){
      // store in image buffer, update counter
      imgJpegBuffer[inBuffCounter] = serBuffer[i];

  // if EOI detected
  if ((imgJpegBuffer[inBuffCounter-1] == 0xd9) &&
          (imgJpegBuffer[inBuffCounter-2] == 0xff)) {
    // clean up counter
    inBuffCounter = 0;
    try {
      // update canvas - array to image
    } catch (IOException e) {

  // if in a loop call startCapture()
  if (isOnLoop){

Then display the image:

private void updateJpegCapturedImage() throws IOException{

  try {
    // convert array to image (BufferedImage) using ByteArrayInputStream(imgJpegBuffer));
    // clear canvas, display image on canvas, remain canvas
    canvasZoom.setImage(img, 1);
  } catch (IOException e) {

Where img definition is:

BufferedImage img = new BufferedImage(320, 240, BufferedImage.TYPE_INT_RGB);

I guess are more elegant ways and may be better ways to write Java code but this works for me. Any feedback will be definitely appreciated.


2 thoughts on “Java – convert byte array to image (jpeg)

  1. Thanks for this. I am mocking around with OV2640 and LPC1768. As I am only starating and learning a whole lot – what is the best way to get video from OV2640 and display it on the PC? What software are you using?

    • Hi Miko, thank you for your interest. I am not using any software. I developed a java client, this is why I posted this entry. Main reason is to have a portable solution working on OSX/Windows/Linux…

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s