Jason Jason - 2 years ago 135
Java Question

Sending a Matlab Image to an Android tablet

I have developed an Android app that connects with a laptop running Matlab over Bluetooth SPP. I am able to send strings back and forth easily and I am now interested in sending an image from Matlab to display on tablet (48x64 grayscale would be sufficient). I am unsure how to package an image and send it over at Matlab serial port. I am guessing you cannot just use fprintf or fwrite.

This is what I think the Android side might look like

public void drawImage(byte[] buffer){
ImageView camView = (ImageView)findViewById(R.id.camView);
Bitmap myBitmap = BitmapFactory.decodeByteArray(buffer, 0, buffer.length);
Log.d(TAG,"decoded image");
if(myBitmap != null){
Log.d(TAG,"Trying to display...");
Log.d(TAG, "Bitmap = null");
}// end drawImage

Any advice on either the Andriod or Matlab side would be greatly appreciated. Thanks!

Answer Source

So I got it working. Basically the issue was that I was not sending the image with the proper compression (either .jpg or .png). I found that if you have a Matlab image which Matlab represents simply as a matrix of pixel values regardless of compression you need to create a java BufferedImage in order to properly construct the byte array so you can decode it on the Android side.

The Matlab side

import java.awt.*;
import java.io.*;
import java.util.*;
import javax.imageio.*;
serCam = InitUSBcamera;  % initialize USB camera as a serial port
type = java.lang.String('jpg'); % translating matlab to java 
outputStream = ByteArrayOutputStream; % create java output stream
im = getsnapshot(serCam);  % get an image from the camera
im2 = imresize(im, [96,128],'nearest');  % reduce the size 
im3 = im2java2d(im2); % create java Buffered Image
ImageIO.write(im3, type, outputStream);
bytes = outputStream.toByteArray();
fwrite(serTablet, bytes, 'int8') % send the image // changed to async 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download