Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload images to Imgur from Mathematica

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 uploader.

How can we create a function imgur[g_] that will rasterize its argument (making sure that the final size is not wider than the width of StackOverflow posts), convert it to PNG, upload it to imgur, and return a ready to be pasted MarkDown line such as ![Mathematica graphic](http://i.imgur.com/ZENa4.jpg) ?

Useful references:

  • Imgur API
  • Example of using POST request from Mathematica on WRI blog (posting to Twitter) by ragfield
  • Example of using POST requests from Mathematica on SO (uploading to ifile.it)

I failed to adapt this latter method to uploading an image without exporting it to a file first.


Warning, use with care! StackOverflow uses a separate imgur installation that keep images indefinitely. If you use the main imgur, the images will disappear after 6 months if no one views them. Unfortunately as of 2011 November there seems to be no official way to upload images to StackOverflow programmatically.


Update: See below a solution for uploading to StackOverflow directly.

like image 359
Szabolcs Avatar asked Nov 07 '11 15:11

Szabolcs


1 Answers

A little bird just informed me of a Mathematica solution to this question (the underlying implementation still uses JLink, but this answer hides all the java related code):

imgur[expr_] := Module[  {url, key, image, data, xml, imgurUrl},  url = "http://api.imgur.com/2/upload";  key = "c07bc3fb59ef878d5e23a0c4972fbb29";  image = Fold[ExportString, expr, {"PNG", "Base64"}];  xml = Import[url,    "XML", "RequestMethod" -> "POST",    "RequestParameters" -> {"key" -> key, "image" -> image}];  imgurUrl = Cases[xml, XMLElement["original", {}, {string_}] :> string,    Infinity][[1]];  "![Mathematica graphic](" <> imgurUrl <> ")" ] 

This is V8 only and the XML import options "RequestMethod" and "RequestParameters" are undocumented and experimental (and therefore subject to change).

like image 171
Arnoud Buzing Avatar answered Oct 15 '22 07:10

Arnoud Buzing