Read binary data from an image and save it with JavaScript

后端 未结 1 1005
予麋鹿
予麋鹿 2021-02-09 10:13

I want to read the binary data of an image and then save it again to my local disk with JavaScript.

I wrote a small demo that shows this use-case. To read the file I us

1条回答
  •  执笔经年
    2021-02-09 10:34

    I have tested this code on your fiddle and it has worked like a charm:

      var contentType = '';
    
      window.saveImage = function() {
        var textToWrite = document.getElementById("inputTextToSave").value;
    
        var splittedTextToWrite = textToWrite.split(",");
    
        var u16 = new Uint16Array(splittedTextToWrite.length);
    
          for(i=0; i

    I'm not an expert on the new HTML5 APIs, but I will try to explain a bit what I have done.

    1) I have saved a PNG to disk. (photo.png)

    2) If you have Linux, you can see the contents of the file in hexadecimal format with this command od -cx photo.png. If not you need some hexadecimal editor.

    The first lines of photo.png in hexadecimal show something like this:

           211   P   N   G  \r  \n 032  \n  \0  \0  \0  \r   I   H   D   R
    
           5089    474e    0a0d    0a1a    0000    0d00    4849    5244
    

    Each pair of numbers in the second line represent the hexadecimal codification of the symbol above: 5089 is the codification of 211 P, 50 is the hex value for P and 89 for 211 (little endian codification, the first two bytes encodes the second symbol, the last two encodes the first symbol)

    3) Instead of read the file as a binaryString, I read it as an ArrayBuffer (it doesn't make encoding conversions).

    4) When the file is read, I transform the ArrayBuffer into a Uint16Array, and store each value in an array to show its decimal value on your text area. It shows the values as a list of decimal numbers, comma separated. The first decimal number will in this case will be 20617, which is the decimal equivalent for the 5089 hexadecimal.

    5) Prior to saving the file, some simple code splits the decimal values and add them to a new Uint16Array.

    It worked for me... It's a bit confusing and probably someone will get a better & more efficient approach using the APIs in another way.

    0 讨论(0)
提交回复
热议问题