Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

From raw bits to jpeg without writing into a file

I have a real time application which receives jpg images coded in base64. I do not know how to show the image in matlab without having to save the image in the disk and open it afterwards.

This is the code I have so far, that saves the image in the disk before showing it:

raw = base64decode(imageBase64, '', 'java'); 
fid = fopen('buffer.jpg', 'wb');
fwrite(fid, raw, 'uint8'); 
fclose(fid);
I = imread('buffer.jpg');              
imshow(I);

Thanks!

like image 533
kahlo Avatar asked Sep 06 '13 13:09

kahlo


1 Answers

You can do it with the help of Java. Example:

% get a stream of bytes representing an endcoded JPEG image
% (in your case you have this by decoding the base64 string)
fid = fopen('test.jpg', 'rb');
b = fread(fid, Inf, '*uint8');
fclose(fid);

% decode image stream using Java
jImg = javax.imageio.ImageIO.read(java.io.ByteArrayInputStream(b));
h = jImg.getHeight;
w = jImg.getWidth;

% convert Java Image to MATLAB image
p = reshape(typecast(jImg.getData.getDataStorage, 'uint8'), [3,w,h]);
img = cat(3, ...
        transpose(reshape(p(3,:,:), [w,h])), ...
        transpose(reshape(p(2,:,:), [w,h])), ...
        transpose(reshape(p(1,:,:), [w,h])));

% check results against directly reading the image using IMREAD
img2 = imread('test.jpg');
assert(isequal(img,img2))

The first part of decoding the JPEG byte stream is based on this answer:

JPEG decoding when data is given in array

The last part converting Java images to MATLAB was based on this solution page:

How can I convert a "Java Image" object into a MATLAB image matrix?


That last part could also be re-written as:

p = typecast(jImg.getData.getDataStorage, 'uint8');
img = permute(reshape(p, [3 w h]), [3 2 1]);
img = img(:,:,[3 2 1]);

imshow(img)
like image 170
Amro Avatar answered Oct 01 '22 03:10

Amro