From raw bits to jpeg without writing into a file

后端 未结 1 1004
南旧
南旧 2020-12-19 06:29

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

相关标签:
1条回答
  • 2020-12-19 07:07

    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)
    
    0 讨论(0)
提交回复
热议问题