6
$\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$
5
$\begingroup$

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"]
(*"http://i.stack.imgur.com/WD80b.png"*)

Remember to remove the double quotes before accessing.

$\endgroup$
  • $\begingroup$ That java code mislead me.Orz... $\endgroup$ – yode Apr 5 '17 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$ – J. M. will be back soon Apr 5 '17 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$ – happy fish Apr 5 '17 at 5:35
  • $\begingroup$ Ah. In that case, the StringCases[] code I gave should work no matter what the file extension is. $\endgroup$ – J. M. will be back soon Apr 5 '17 at 6:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.