从原始位到JPEG格式,无需写入文件

7
我有一个实时应用程序,它接收以base64编码的jpg图像。我不知道如何在Matlab中显示图像,而无需将图像保存到磁盘并在之后打开。
这是我目前拥有的代码,它在显示图像之前将其保存到磁盘中:
raw = base64decode(imageBase64, '', 'java'); 
fid = fopen('buffer.jpg', 'wb');
fwrite(fid, raw, 'uint8'); 
fclose(fid);
I = imread('buffer.jpg');              
imshow(I);

谢谢!

1个回答

9

您可以借助Java完成。例如:

% 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))

首先,解码JPEG字节流的第一部分是基于以下答案:JPEG decoding when data is given in array
而将Java图像转换为MATLAB的最后一部分则基于以下解决方案页面:How can I convert a "Java Image" object into a MATLAB image matrix? 最后一部分也可以重写为:
p = typecast(jImg.getData.getDataStorage, 'uint8');
img = permute(reshape(p, [3 w h]), [3 2 1]);
img = img(:,:,[3 2 1]);

imshow(img)

根据这个答案,一位同行为FEX贡献了一个MATLAB工具:https://www.mathworks.com/matlabcentral/fileexchange/53716-decodejpeg - Carl Witthoft

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接