问题描述
这是所有mathematica
标签关注者的挑战.通过创建一个 imgur 上传器,让我们更加方便地将图像从Mathematica插入SO帖子中.
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.
我们如何创建一个函数imgur[g_]
,该函数将对其参数进行栅格化(确保最终大小不大于StackOverflow帖子的宽度),将其转换为PNG,将其上传到imgur,并返回一个现成的粘贴 MarkDown 行,例如![Mathematica graphic](http://i.imgur.com/ZENa4.jpg)
吗?
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)
?
有用的参考文献:
- Imgur API
- 在WRI博客上使用来自Mathematica的POST请求的示例(发布到Twitter)通过 ragfield
- 在Ma上使用来自Mathematica的POST请求的示例(上传到ifile.it)
- 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.
警告,请小心使用!!StackOverflow使用单独的imgur安装可无限期保存图片.如果您使用主要imgur,则如果没有人观看,图像将在6个月后消失.不幸的是,截至2011年11月,似乎没有官方方式以编程方式将图像上传到StackOverflow.
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.
更新:参见下文直接上传到StackOverflow 的解决方案 em>.
Update: See below a solution for uploading to StackOverflow directly.
推荐答案
一只小鸟刚刚告诉我有关该问题的 Mathematica 解决方案(底层实现仍使用JLink,但此答案隐藏了所有内容Java相关代码):
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 <> ")"
]
这仅是V8版本,XML
导入选项"RequestMethod"
和"RequestParameters"
未记录且仍处于实验阶段(因此可能会发生变化).
This is V8 only and the XML
import options "RequestMethod"
and "RequestParameters"
are undocumented and experimental (and therefore subject to change).
这篇关于从Mathematica将图像上传到Imgur的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!