从原始位到jpeg,无需写入文件 [英] From raw bits to jpeg without writing into a file

查看:120
本文介绍了从原始位到jpeg,无需写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实时应用程序,它接收以base64编码的jpg图像.我不知道如何在matlab中显示图像,而不必将图像保存在磁盘中并随后将其打开.

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

谢谢!

推荐答案

您可以借助Java来做到这一点.示例:

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

解码JPEG字节流的第一部分基于以下答案:

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

在数组中提供数据时进行JPEG解码

将Java图像转换为MATLAB的最后一部分基于此解决方案页面:

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

如何将"Java Image"对象转换为MATLAB图像矩阵?


最后一部分也可以改写为:


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)

这篇关于从原始位到jpeg,无需写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆