Upload images to Imgur from Mathematica

后端 未结 3 971
有刺的猬
有刺的猬 2020-12-13 03:30

Here\'s a challenge to all mathematica tag followers. Let\'s make it a lot more convenient to insert images into SO post from Mathematica by creating an imgur

3条回答
  •  半阙折子戏
    2020-12-13 04:30

    Note: This is using the anonymous imgur uploader with my anonymous key. The imgur site restricts uploads to 50 uploads/hour which should be fine normally, but this may cause a problem if a lot of people try this simultaneously. So please get your own anonymous key here:

    http://imgur.com/register/api_anon

    And then replace the key in the code below with your own key (thanks!).

    The trickiest part to code was the conversion from a Mathematica expression to PNG image to Base64 encoding to URL encoding. There are about a 1,000 ways to do it wrong and I think I managed to try them all.

    The code breaks down into a few pieces:

    • Construct the POST url
    • Make the HTTP connection
    • Send the POST url
    • Read back the result, which is XML
    • Extract the imgur url from the XML
    • Format the imgur url as markdown (or as a Mathematica Hyperlink function).

    Here is the code:

    imgur[expr_] :=
     Module[{url, key, image, data, jUrl, jConn, jWriter, jInput, buffer,
       byte, xml, imgurUrl},
      Needs["JLink`"];
      JLink`JavaBlock[
       JLink`LoadJavaClass["java.net.URLEncoder"];
       url = "http://api.imgur.com/2/upload";
       key = "c07bc3fb59ef878d5e23a0c4972fbb29";
       image = ExportString[ExportString[expr, "PNG"], "Base64"];
       data =
        URLEncoder`encode["key"   , "UTF-8"] <> "=" <>
        URLEncoder`encode[ key    , "UTF-8"] <> "&" <>
        URLEncoder`encode["image" , "UTF-8"] <> "=" <>
        URLEncoder`encode[ image  , "UTF-8"] ;
       jUrl = JLink`JavaNew["java.net.URL", url];
       jConn = jUrl@openConnection[];
       jConn@setDoOutput[True];
       jWriter =
        JLink`JavaNew["java.io.OutputStreamWriter",
         jConn@getOutputStream[]];
       jWriter@write[data];
       jWriter@flush[];
       jInput = jConn@getInputStream[];
       buffer = {};
       While[(byte = jInput@read[]; byte >= 0), AppendTo[buffer, byte]];
       ];
      xml = ImportString[FromCharacterCode[buffer], "XML"];
      imgurUrl =
       Cases[xml,
         XMLElement["original", {}, {string_}] :>
          string, \[Infinity]][[1]];
      "![Mathematica graphic](" <> imgurUrl <> ")"
      ]
    

    Testing:

    In[]:= g = Graphics[{Blue, Disk[]}, PlotRange -> 1.2, ImageSize -> Small];
           pic = Overlay[{Blur[Binarize@g, 10], g}];
           imgur[pic]
    
    Out[]= ![Mathematica graphic](http://i.imgur.com/eGOlL.png)
    

    And the actual image:

    Mathematica graphic

提交回复
热议问题