Display image from blob using javascript and websockets

后端 未结 6 1374
春和景丽
春和景丽 2020-11-29 22:05

I\'m currently working on a WebSocket application that is displaying images send by a C++ server. I\'ve seen a couple of topics around there but I can\'t seem to get rid of

6条回答
  •  旧时难觅i
    2020-11-29 22:31

    This is very simple using a Blob:

    // Small red dot image
    const content = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 5, 0, 0, 0, 5, 8, 6, 0, 0, 0, 141, 111, 38, 229, 0, 0, 0, 28, 73, 68, 65, 84, 8, 215, 99, 248, 255, 255, 63, 195, 127, 6, 32, 5, 195, 32, 18, 132, 208, 49, 241, 130, 88, 205, 4, 0, 14, 245, 53, 203, 209, 142, 14, 31, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130]);
    
    document.getElementById('my-img').src = URL.createObjectURL(
      new Blob([content.buffer], { type: 'image/png' } /* (1) */)
    );
    Should display a small red dot: 

    Works also with a simple array instead of Uint8Array:

    // Small red dot image
    const content = [137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 5, 0, 0, 0, 5, 8, 6, 0, 0, 0, 141, 111, 38, 229, 0, 0, 0, 28, 73, 68, 65, 84, 8, 215, 99, 248, 255, 255, 63, 195, 127, 6, 32, 5, 195, 32, 18, 132, 208, 49, 241, 130, 88, 205, 4, 0, 14, 245, 53, 203, 209, 142, 14, 31, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130];
    
    document.getElementById('my-img').src = URL.createObjectURL(
      new Blob(content /* (1) */)
    );
    

    (1) It works without specifying the Blob MIME type.

提交回复
热议问题