How to create png image file-object from numpy array in python without saving to disk (for http request)



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I need to submit PNG-images to a blackbox server with a http request. I use python3 to generate images in a numpy 64x64x3 array. What I currently do is:



  1. Generate image

  2. Save image with scipy.misc.toimage to disk

  3. Open saved image file from disk

  4. Use requests module to send http requests with the image opened image file object in it

This works perfectly fine, but I want to get rid of step 2 and 3, so I do not need to save my object to disk first and then load it again. Instead I would like to convert my numpy array in a file-object that is compatible with the http server and send it directly. (Like one you get from open() )



I know it is easy to convert from numpy array to PNG-image with PIL for example, but I only find how to do that combined with saving to disk in one function.



Thank you very much for any help!



This is my code so far:



import numpy as np
import requests
from scipy.misc import toimage

arr = generate64x64x3ImageWithNumpy()
toimage(arr, cmin=0.0, cmax=255.0).save('tmp.png')
d = 'key':API_KEY
f= 'image': open('tmp.png', 'rb')
result = requests.post(SERVER_URL, files=f, data=d)


I want this:



arr = generate64x64x3ImageWithNumpy()

not_on_disk = numpyArrayToPNGImageWithoutSavingOnDisk(arr)

d = 'key':API_KEY
f = 'image': not_on_disk
result = requests.post(SERVER_URL, files=f, data=d)









share|improve this question




























    1















    I need to submit PNG-images to a blackbox server with a http request. I use python3 to generate images in a numpy 64x64x3 array. What I currently do is:



    1. Generate image

    2. Save image with scipy.misc.toimage to disk

    3. Open saved image file from disk

    4. Use requests module to send http requests with the image opened image file object in it

    This works perfectly fine, but I want to get rid of step 2 and 3, so I do not need to save my object to disk first and then load it again. Instead I would like to convert my numpy array in a file-object that is compatible with the http server and send it directly. (Like one you get from open() )



    I know it is easy to convert from numpy array to PNG-image with PIL for example, but I only find how to do that combined with saving to disk in one function.



    Thank you very much for any help!



    This is my code so far:



    import numpy as np
    import requests
    from scipy.misc import toimage

    arr = generate64x64x3ImageWithNumpy()
    toimage(arr, cmin=0.0, cmax=255.0).save('tmp.png')
    d = 'key':API_KEY
    f= 'image': open('tmp.png', 'rb')
    result = requests.post(SERVER_URL, files=f, data=d)


    I want this:



    arr = generate64x64x3ImageWithNumpy()

    not_on_disk = numpyArrayToPNGImageWithoutSavingOnDisk(arr)

    d = 'key':API_KEY
    f = 'image': not_on_disk
    result = requests.post(SERVER_URL, files=f, data=d)









    share|improve this question
























      1












      1








      1








      I need to submit PNG-images to a blackbox server with a http request. I use python3 to generate images in a numpy 64x64x3 array. What I currently do is:



      1. Generate image

      2. Save image with scipy.misc.toimage to disk

      3. Open saved image file from disk

      4. Use requests module to send http requests with the image opened image file object in it

      This works perfectly fine, but I want to get rid of step 2 and 3, so I do not need to save my object to disk first and then load it again. Instead I would like to convert my numpy array in a file-object that is compatible with the http server and send it directly. (Like one you get from open() )



      I know it is easy to convert from numpy array to PNG-image with PIL for example, but I only find how to do that combined with saving to disk in one function.



      Thank you very much for any help!



      This is my code so far:



      import numpy as np
      import requests
      from scipy.misc import toimage

      arr = generate64x64x3ImageWithNumpy()
      toimage(arr, cmin=0.0, cmax=255.0).save('tmp.png')
      d = 'key':API_KEY
      f= 'image': open('tmp.png', 'rb')
      result = requests.post(SERVER_URL, files=f, data=d)


      I want this:



      arr = generate64x64x3ImageWithNumpy()

      not_on_disk = numpyArrayToPNGImageWithoutSavingOnDisk(arr)

      d = 'key':API_KEY
      f = 'image': not_on_disk
      result = requests.post(SERVER_URL, files=f, data=d)









      share|improve this question














      I need to submit PNG-images to a blackbox server with a http request. I use python3 to generate images in a numpy 64x64x3 array. What I currently do is:



      1. Generate image

      2. Save image with scipy.misc.toimage to disk

      3. Open saved image file from disk

      4. Use requests module to send http requests with the image opened image file object in it

      This works perfectly fine, but I want to get rid of step 2 and 3, so I do not need to save my object to disk first and then load it again. Instead I would like to convert my numpy array in a file-object that is compatible with the http server and send it directly. (Like one you get from open() )



      I know it is easy to convert from numpy array to PNG-image with PIL for example, but I only find how to do that combined with saving to disk in one function.



      Thank you very much for any help!



      This is my code so far:



      import numpy as np
      import requests
      from scipy.misc import toimage

      arr = generate64x64x3ImageWithNumpy()
      toimage(arr, cmin=0.0, cmax=255.0).save('tmp.png')
      d = 'key':API_KEY
      f= 'image': open('tmp.png', 'rb')
      result = requests.post(SERVER_URL, files=f, data=d)


      I want this:



      arr = generate64x64x3ImageWithNumpy()

      not_on_disk = numpyArrayToPNGImageWithoutSavingOnDisk(arr)

      d = 'key':API_KEY
      f = 'image': not_on_disk
      result = requests.post(SERVER_URL, files=f, data=d)






      python numpy http request png






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 16 '18 at 14:03









      jobuschjobusch

      112




      112






















          1 Answer
          1






          active

          oldest

          votes


















          1














          You can use an in memory iostream with savefig (https://docs.python.org/3/library/io.html#io.BytesIO)



          import io
          tmpFile = io.BytesIO()
          savefig(tmpFile, format='png')


          To verify that this worked tmpFile can be compared with the actual file as saved to disk.



          # Get contents of tmpFile
          tmpFile.seek(0)
          not_on_disk = tmpFile.read(-1)

          # Save to and load from disk
          fname = 'tmp.png'
          savefig(fname)
          on_disk = open(fname, 'rb').read(-1)

          >>>not_on_disk == on_disk
          True


          Edit You're looking at using scipy and pil rather than matplotlib but the answer should work the same, including the format keyword for saving.






          share|improve this answer

























          • Thank you very much for your fast response! :) But what variable do I need to pass to my http request? Is it tmpFile or not_on_disk? with open(...) I have type _io.BufferedReader, so this is what I want. tmpFile is of type BytesIO and not_on_disk is of type _bytes. Any way to convert? Also if I try to open not_on_disk I get "embedded null byte"-error. If I use PIL to open I get PngImageFile object has no attribute read when I make the request. Sorry for my little understanding.

            – jobusch
            Nov 16 '18 at 17:52












          • It looks like the requests.post takes a file handle, so you would want to pass tmpFile (after calling tmpFile.seek(0) to set the beginning of the file).

            – user2699
            Nov 16 '18 at 19:14











          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53339373%2fhow-to-create-png-image-file-object-from-numpy-array-in-python-without-saving-to%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          You can use an in memory iostream with savefig (https://docs.python.org/3/library/io.html#io.BytesIO)



          import io
          tmpFile = io.BytesIO()
          savefig(tmpFile, format='png')


          To verify that this worked tmpFile can be compared with the actual file as saved to disk.



          # Get contents of tmpFile
          tmpFile.seek(0)
          not_on_disk = tmpFile.read(-1)

          # Save to and load from disk
          fname = 'tmp.png'
          savefig(fname)
          on_disk = open(fname, 'rb').read(-1)

          >>>not_on_disk == on_disk
          True


          Edit You're looking at using scipy and pil rather than matplotlib but the answer should work the same, including the format keyword for saving.






          share|improve this answer

























          • Thank you very much for your fast response! :) But what variable do I need to pass to my http request? Is it tmpFile or not_on_disk? with open(...) I have type _io.BufferedReader, so this is what I want. tmpFile is of type BytesIO and not_on_disk is of type _bytes. Any way to convert? Also if I try to open not_on_disk I get "embedded null byte"-error. If I use PIL to open I get PngImageFile object has no attribute read when I make the request. Sorry for my little understanding.

            – jobusch
            Nov 16 '18 at 17:52












          • It looks like the requests.post takes a file handle, so you would want to pass tmpFile (after calling tmpFile.seek(0) to set the beginning of the file).

            – user2699
            Nov 16 '18 at 19:14















          1














          You can use an in memory iostream with savefig (https://docs.python.org/3/library/io.html#io.BytesIO)



          import io
          tmpFile = io.BytesIO()
          savefig(tmpFile, format='png')


          To verify that this worked tmpFile can be compared with the actual file as saved to disk.



          # Get contents of tmpFile
          tmpFile.seek(0)
          not_on_disk = tmpFile.read(-1)

          # Save to and load from disk
          fname = 'tmp.png'
          savefig(fname)
          on_disk = open(fname, 'rb').read(-1)

          >>>not_on_disk == on_disk
          True


          Edit You're looking at using scipy and pil rather than matplotlib but the answer should work the same, including the format keyword for saving.






          share|improve this answer

























          • Thank you very much for your fast response! :) But what variable do I need to pass to my http request? Is it tmpFile or not_on_disk? with open(...) I have type _io.BufferedReader, so this is what I want. tmpFile is of type BytesIO and not_on_disk is of type _bytes. Any way to convert? Also if I try to open not_on_disk I get "embedded null byte"-error. If I use PIL to open I get PngImageFile object has no attribute read when I make the request. Sorry for my little understanding.

            – jobusch
            Nov 16 '18 at 17:52












          • It looks like the requests.post takes a file handle, so you would want to pass tmpFile (after calling tmpFile.seek(0) to set the beginning of the file).

            – user2699
            Nov 16 '18 at 19:14













          1












          1








          1







          You can use an in memory iostream with savefig (https://docs.python.org/3/library/io.html#io.BytesIO)



          import io
          tmpFile = io.BytesIO()
          savefig(tmpFile, format='png')


          To verify that this worked tmpFile can be compared with the actual file as saved to disk.



          # Get contents of tmpFile
          tmpFile.seek(0)
          not_on_disk = tmpFile.read(-1)

          # Save to and load from disk
          fname = 'tmp.png'
          savefig(fname)
          on_disk = open(fname, 'rb').read(-1)

          >>>not_on_disk == on_disk
          True


          Edit You're looking at using scipy and pil rather than matplotlib but the answer should work the same, including the format keyword for saving.






          share|improve this answer















          You can use an in memory iostream with savefig (https://docs.python.org/3/library/io.html#io.BytesIO)



          import io
          tmpFile = io.BytesIO()
          savefig(tmpFile, format='png')


          To verify that this worked tmpFile can be compared with the actual file as saved to disk.



          # Get contents of tmpFile
          tmpFile.seek(0)
          not_on_disk = tmpFile.read(-1)

          # Save to and load from disk
          fname = 'tmp.png'
          savefig(fname)
          on_disk = open(fname, 'rb').read(-1)

          >>>not_on_disk == on_disk
          True


          Edit You're looking at using scipy and pil rather than matplotlib but the answer should work the same, including the format keyword for saving.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 16 '18 at 14:50

























          answered Nov 16 '18 at 14:40









          user2699user2699

          1,449720




          1,449720












          • Thank you very much for your fast response! :) But what variable do I need to pass to my http request? Is it tmpFile or not_on_disk? with open(...) I have type _io.BufferedReader, so this is what I want. tmpFile is of type BytesIO and not_on_disk is of type _bytes. Any way to convert? Also if I try to open not_on_disk I get "embedded null byte"-error. If I use PIL to open I get PngImageFile object has no attribute read when I make the request. Sorry for my little understanding.

            – jobusch
            Nov 16 '18 at 17:52












          • It looks like the requests.post takes a file handle, so you would want to pass tmpFile (after calling tmpFile.seek(0) to set the beginning of the file).

            – user2699
            Nov 16 '18 at 19:14

















          • Thank you very much for your fast response! :) But what variable do I need to pass to my http request? Is it tmpFile or not_on_disk? with open(...) I have type _io.BufferedReader, so this is what I want. tmpFile is of type BytesIO and not_on_disk is of type _bytes. Any way to convert? Also if I try to open not_on_disk I get "embedded null byte"-error. If I use PIL to open I get PngImageFile object has no attribute read when I make the request. Sorry for my little understanding.

            – jobusch
            Nov 16 '18 at 17:52












          • It looks like the requests.post takes a file handle, so you would want to pass tmpFile (after calling tmpFile.seek(0) to set the beginning of the file).

            – user2699
            Nov 16 '18 at 19:14
















          Thank you very much for your fast response! :) But what variable do I need to pass to my http request? Is it tmpFile or not_on_disk? with open(...) I have type _io.BufferedReader, so this is what I want. tmpFile is of type BytesIO and not_on_disk is of type _bytes. Any way to convert? Also if I try to open not_on_disk I get "embedded null byte"-error. If I use PIL to open I get PngImageFile object has no attribute read when I make the request. Sorry for my little understanding.

          – jobusch
          Nov 16 '18 at 17:52






          Thank you very much for your fast response! :) But what variable do I need to pass to my http request? Is it tmpFile or not_on_disk? with open(...) I have type _io.BufferedReader, so this is what I want. tmpFile is of type BytesIO and not_on_disk is of type _bytes. Any way to convert? Also if I try to open not_on_disk I get "embedded null byte"-error. If I use PIL to open I get PngImageFile object has no attribute read when I make the request. Sorry for my little understanding.

          – jobusch
          Nov 16 '18 at 17:52














          It looks like the requests.post takes a file handle, so you would want to pass tmpFile (after calling tmpFile.seek(0) to set the beginning of the file).

          – user2699
          Nov 16 '18 at 19:14





          It looks like the requests.post takes a file handle, so you would want to pass tmpFile (after calling tmpFile.seek(0) to set the beginning of the file).

          – user2699
          Nov 16 '18 at 19:14



















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53339373%2fhow-to-create-png-image-file-object-from-numpy-array-in-python-without-saving-to%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Top Tejano songwriter Luis Silva dead of heart attack at 64

          ReactJS Fetched API data displays live - need Data displayed static

          Evgeni Malkin