7
$\begingroup$

This is not a duplicate of How to call Imgur API.

I tried to upload to imgur using its API, but (as my friends test) the API of imgur cannot be called in Chinese mainland. Then I found that halirutan has a technology to upload an image to imgur even without any account information via http://stackoverflow.com/upload/image. Now I can upload image to imgur by his function SEUploader`sendImage. Little pity is that he implemented it with Java code.

We can find his code here. I get nothing after researching his Java code. Can we do the same thing in pure Mathematica using new functions introduced in version 11.0 such as HTTPRequest, URLRead and so on?

$\endgroup$
0

1 Answer 1

7
$\begingroup$

Update on June 29th, 2020

Since API has changed, the new code is here:

getFKey[] := 
 First@StringCases[
   URLRead[HTTPRequest["https://stackexchange.com"]]["Body"], 
   "fkey: '" ~~ Shortest[fkey___] ~~ "'" :> fkey]
uploadImageSE[imagePath_] := 
 Module[{req}, 
  req = HTTPRequest[
    "https://mathematica.stackexchange.com/upload/image?method=json&\
https=true", <|Method -> "POST", 
     "Body" -> {"file" -> File[imagePath], "fkey" -> getFKey[]}|>];
  ImportString[URLRead[req]["Body"], "RawJSON"]["UploadedImage"]]

This is expected to work with jpg and png files. You need to input the path to image, just like an upload.

uploadImageSE[imagePath_] := 
 Module[{req}, 
  req = HTTPRequest[
    "http://stackoverflow.com/upload/image", <|
     
     "Body" -> {"image" -> <|"Content" -> File[imagePath], 
         "MIMEType" -> "image/png"|>}
     |>];
  StringCases[URLRead[req, "Body"], "http" ~~ __ ~~ ".jpg" | ".png"] //
    First]


uploadImageSE["/Users/xxx/Downloads/test.png"]
(*"https://i.sstatic.net/WD80b.png"*)

Remember to remove the double quotes before accessing.

$\endgroup$
4
  • $\begingroup$ That java code mislead me.Orz... $\endgroup$ Commented Apr 5, 2017 at 3:38
  • $\begingroup$ If you've already set "MIMEType" -> "image/png", then you don't need to search for ".jpg". You can do something like First[StringCases[URLRead[req, "Body"], RegularExpression["closeDialog\\(\"(.+)\"\\)"] -> "$1"]]. $\endgroup$ Commented Apr 5, 2017 at 4:35
  • $\begingroup$ @J.M. even if I set it to be png, I found the uploaded file to be .jpg sometimes when the original file is .jpg $\endgroup$ Commented Apr 5, 2017 at 5:35
  • $\begingroup$ Ah. In that case, the StringCases[] code I gave should work no matter what the file extension is. $\endgroup$ Commented Apr 5, 2017 at 6:25

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.