Receive txt and generate image from text

Asked

Viewed 1,756 times

0

Hello guys! I have a problem that I cannot solve in any way. I have tried a lot and I have not gotten anywhere. In the company where I work we use proprietary language, which I hate. When I request an image via $.ajax() (jQuery) the only possible return I have is a string. This string is in binary. From this string I have to generate an image. For example: if we open an image (jpeg, png or jpg extension) with the notepad, what will appear is a lot of characters. If you copy this text, paste it into the Notepad and save it as txt, you can change the extension of this file to . jpeg and what was once a text (.txt) becomes an image. Ok...

That is, the blessed proprietary language of the company where I work sends me these characters/ text, but I cannot generate an image and present it on the screen.

I read about Blob. According to some posts I found, it is possible to generate an image if I create a Blob object with the characters I received.

I believe it’s something with the blob type:

var myBlob = new Blob([response], {type:"text/jpg"});

Here is an excerpt from the ajax request:

$.ajax({
    url: url,
    method: "POST",
    success: function(response){
               var myBlob = new Blob([response], {type: "text/jpeg"});
    }
 });

Someone knows how to do it?

  • Hello! I don’t know exactly what you need to do with the string (text). But, we recently used in a project a lib for angular that generates images from the initials of the names, similar to what GMAIL does. For example, Tiago Silva creates a TL image. This is done locally, by the angular. Maybe it’s a starting point for you: http://uttesh.com/ngletteravatar/ Hug and good luck!

  • 1

    Would I write a "proxy" REST service that calls your original service and already returns something in Base64? This would be the cleanest solution to avoid hacking Javascript. Otherwise I think you’re on the "right" path, see that reply from Soen.

2 answers

1

If the return is a Base64, it is possible to concatenate the string with the src element, using the markings data:image/gif;base64:

var base64String = "iVBORw0KGgoAAAANSUhEUgAAAC4AAAAuCAIAAADY27xgAAAAA3NCSVQICAjb4U\/gAAAAlnpUWHRS\r\nYXcgcHJvZmlsZSB0eXBlIEFQUDEAAHicVY5BDsMgDATvvIInjG0w8BxUkSpS1Vb5\/6EHSNvsZaVZ\r\na9fhPp7j2G\/xfby2\/TFCjDFGkRpSS007UJlSMEFQoCzk073VQgJk8cFFGW9uLsV8XhhAmz2JhUxN\r\nDaTPfHV9PXf+N\/L51yldmf46s1qzuth1S2w+AUD4AOdVNXTvLP3VAAAKV0lEQVRYhc2YWahm2VWA\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Hvx4uXPPU7dU3rmurq9M\/66kdxKLiL7B9c2N7eRLDMzMRER0cmkTklHo256X9OcNDWNK8tK\r\nNUCKzs2K7qc2LvzaE3Q9fagRwtHO9h+pHojtEXZOJlcuXtxClHcnCUjkmjCbNd1uZi3FGBe5WlNK\r\n6hpflvMse+ni5d8gAjztN1q9iO\/1Hx90vnK4\/9fHx3\/Lhon6k8mPr66MRQIgIxK0AxZIs5lrGm8t\r\nZ5YSaIxBY9RFRRxSikSrRF0AE7WXZZ9YW3\/ZmPfi5hmmTiGcHB1+cz57E7GZzq6LcL+3S6yLtJsQ\r\nIKlqVTVlOY\/q8vyqSB\/SMYAHYIACcMmYzSz\/iX7\/SlHk+FBH9owDMABQbcr598r5W2U5nk6LBFFk\r\nLmaG2CAmoq7IRtF9qdv7pMiFECDGoKqISMyG6Qmj5WdGeRhrEkLtHITAImAtG9NFlOc77X+E8uHK\r\n\/8oI+fnk\/xHKDwFCDVuRTRk4QwAAAABJRU5ErkJggg==";

function adicionarImg(imagem) {
   document.querySelector("#image").src = "data:image/gif;base64,"+ imagem;
}

adicionarImg(base64String);
<img id="image" />

  • The code of the open image in the notepad is something like this, only in the case I took a good piece, because it doesn’t fit here.. &#xA;&#xA;Olha: &#xA;ÿØÿà JFIF ÿÛ C $" &0P40,,0bFJ:Ptfzxrfpn€¸œ€ˆ®Šnp Ú¢®¾ÄÎÐÎ|šâòàÈð¸ÊÎÆÿÛ C"$$0*0^44^Æ„p„ÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÿÀ ~" ÿÄ

  • the image is a jpg or jpeg image. Open an image in this format with the Notepad or Notepad++...

  • According to the question tags he’s using AngularJS, then put in attribute ng-src to be consistent with the framework

0

First, we need to treat binary, by default, jQuery doesn’t treat answers as binary, so I found this website the addition of this feature. See the $.ajaxTransport block.

After obtaining this feature, follow the code from . on('click'). It is commented and explaining item by item.

I ran the test on the local machine, it works perfectly. I could not make it work by the code snippet below, because I could not find any location that provides images via ajax requests. If anyone knows, provide the link to make the insertion in the code below please.

$(function() {
  // Extraído do link acima
  $.ajaxTransport("+binary", function(options, originalOptions, jqXHR) {

    // check for conditions and support for blob / arraybuffer response type
    if (window.FormData && ((options.dataType && (options.dataType == 'binary')) || (options.data && ((window.ArrayBuffer && options.data instanceof ArrayBuffer) || (window.Blob && options.data instanceof Blob))))) {
      return {

        // create new XMLHttpRequest
        send: function(headers, callback) {

          // setup all variables
          var xhr = new XMLHttpRequest(),
            url = options.url,
            type = options.type,
            async = options.async || true,

            // blob or arraybuffer. Default is blob
            dataType = options.responseType || "blob",
            data = options.data || null,
            username = options.username || null,
            password = options.password || null;

          xhr.addEventListener('load', function() {
            var data = {};
            data[options.dataType] = xhr.response;

            // make callback and send data
            callback(xhr.status, xhr.statusText, data, xhr.getAllResponseHeaders());
          });

          xhr.open(type, url, async, username, password);

          // setup custom headers
          for (var i in headers) {
            xhr.setRequestHeader(i, headers[i]);
          }

          xhr.responseType = dataType;
          xhr.send(data);
        },
        abort: function() {
          jqXHR.abort();
        }
      };
    }
  });
  // Fim Extraído do link acima

  // Função de clique para chamar o Ajax
  $('.button').on('click', function(e) {

    // Requisição ao servidor
    $.ajax({
      url: "/minha-imagem.jpg",
      type: "GET",
      dataType: "binary",
      processData: false, // Obrigatório
      cache: false, // Opcional
      crossDomain: true,
      success: function(result, status, xhr) {

        // Resgata o tipo mime do arquivo vindo no cabeçalho do pacote
        // Exemplo: image/jpge
        var ct = xhr.getResponseHeader('content-type');

        // Cria o objeto Blog para gerar o base64
        var result = new Blob([result], {
          type: ct
        });

        // Metódo para ler o arquivo
        var reader = new window.FileReader();

        // Leitura do Blog como base64
        reader.readAsDataURL(result);

        // Quando a leitura terminar...
        reader.onloadend = function() {

          // Resgata a string
          base64data = reader.result;

          // Cria o iframe...
          var iframe = $('<iframe></iframe>');
    
          // Adiciona ao src a string base64, caso sempre for imagem, pode ser em um objeto img
          iframe.attr('src', base64data);

          // Insere no HTML o iframe com o conteúdo
          $("#result").html(iframe);
        }
      },
    });
  });
});
<script src="https://unpkg.com/[email protected]/dist/jquery.min.js"></script>

<button class="button">Imagem</button>
<div id="result"></div>

  • 1

    @Jeffersonquesado, the button to execute the code will not work because this image does not exist, I put a remark "I performed the test on the local machine, works perfectly. I could not make it work by the code snippet below, because I could not find any location that provides images via ajax requests. If anyone knows, provide the link to make the insertion in the code below please."

  • sorry, I did not read this excerpt from the reply. I will remove my comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.