Page 1 of 1

Uploading image link to Imgur

Posted: 22 Sep 2020, 13:17
by SyntaxTerror
Hello

I would like to make a code doing this:
  1. upload one or several (let's say up to 10) images to Imgur (preferably without an Imgur account)
  2. apply a RegEx to the imgur links list to put them in BBCode image tags (Image)
I think I can manage to do step #2, but making a code to upload images on Imgur is too difficult for me.
I found this post by @tmplinshi that gives a code to achieve this: https://www.autohotkey.com/boards/viewtopic.php?t=15697 and I could use the clipboard content by adapting it like explained here: https://www.autohotkey.com/boards/viewtopic.php?p=196761#p196761

I tried to run this code after copying an image link (right click/copy image address):

Code: Select all

; Create Imgurl ClientID -- https://api.imgur.com/oauth2/addclient

UploadToImgur(FileName, ClientID = "fbf77ff49c42c8a") {
	return UploadToImgur.DoIt(FileName, ClientID)
}

Class UploadToImgur {

	DoIt(FileName, ClientID) {
		postData := this.FileToStream(FileName)
		header := {"Authorization": "Client-ID " ClientID}
		whr := this.Http("POST", "https://api.imgur.com/3/image",  postData, header)

		if RegExMatch(whr.ResponseText, """link"":""\K[^""]+", result) {
			return StrReplace(result, "\")
		} else {
			RegExMatch(whr.ResponseText, """error"":""\K[^""]+", errMsg)
			throw, errMsg ? errMsg : "Unkown Error"
		}
	}

	FileToStream(FileName) {
		ADO := ComObjCreate("ADODB.Stream")
		ADO.Type := 1 ; adTypeBinary
		ADO.Open()
		ADO.LoadFromFile(FileName)
		Stream := ADO.Read()
		ADO.Close()
		return Stream
	}

	Http(Method, Url, PostData="", Obj_Headers="") {
		whr := ComObjCreate("WinHttp.WinHttpRequest.5.1")
		whr.Open(Method, Url, "True")

		for k, v in Obj_Headers {
			whr.SetRequestHeader(k, v)
		}
		if (Method = "POST") && !Obj_Headers["Content-Type"] {
			whr.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded")
		}

		whr.Send(PostData)
		whr.WaitForResponse()
		return whr
	}
}

ImageFile := clipboard

try {
	result := UploadToImgur(ImageFile)
	MsgBox, 64, Upload Successful!, % result
} catch errMsg {
	MsgBox, 48, Error!, % errMsg
}
But I get an error message (the one from line 55). I tried with different images to no avail.

Maybe Imgur has changed its uploading methods since, or maybe I didn't understand how this code chooses between a registered ClientID or the "default" ID this function is said to provide.

Anyway, I cannot make it work myself, so any help using this code or another similar one would be verry appreciated.

Regards.

Re: Uploading image link to Imgur

Posted: 22 Sep 2020, 16:15
by tmplinshi
https://www.autohotkey.com/boards/viewtopic.php?p=300157#p300157

or:

Code: Select all

#Include ImagePut.ahk ; https://www.autohotkey.com/boards/viewtopic.php?f=6&t=76301

MsgBox % Imgur_UploadFromClipboard()

Imgur_UploadFromClipboard(ClientID := "fbf77ff49c42c8a") {
	body := ClipImageToByteArray()

	whr := ComObjCreate("WinHttp.WinHttpRequest.5.1")
	;whr.SetProxy(2, "localhost:1080")
	whr.Open("POST", "https://api.imgur.com/3/image", true)
	whr.SetRequestHeader("Authorization", "Client-ID " . ClientID)
	whr.Send(body)
	whr.WaitForResponse()

	if RegExMatch(whr.ResponseText, """link"":""\K[^""]+", result) {
		return StrReplace(result, "\")
	} else {
		RegExMatch(whr.ResponseText, """(message|error)"":""\K[^""]+", errMsg)
		throw errMsg ? errMsg : "Unkown Error"
	}
}

ClipImageToByteArray() {
	pStream := ImagePutStream(ClipboardAll)

	DllCall("ole32\GetHGlobalFromStream", "ptr",pStream, "uint*",hData)
	pData := DllCall("GlobalLock", "ptr",hData, "uptr")
	nSize := DllCall("GlobalSize", "uint",pData)

	safeArray := ComObjArray(0x11, nSize) ; Create SAFEARRAY = VT_ARRAY|VT_UI1
	pvData := NumGet(ComObjValue(safeArray) + 12 + (A_PtrSize==8 ? 4 : 0)) ; get pvData memeber
	DllCall("RtlMoveMemory", "ptr", pvData, "ptr", pData, "ptr", nSize)

	DllCall("GlobalUnlock", "ptr",hData)
	DllCall(NumGet(NumGet(pStream + 0, 0, "uptr") + (A_PtrSize * 2), 0, "uptr"), "ptr",pStream)
	DllCall("GlobalFree", "ptr",hData)
	ObjRelease(pStream)
	return safeArray
}

Re: Uploading image link to Imgur

Posted: 22 Sep 2020, 19:38
by SyntaxTerror
For the first code I have an error line 28 "Gdip_CreateBitmapFromClipboard fail: -2"

For the second code, I have an error at line 149: "this line does not conatain a recognised action"

Please don't just throw some code at me, I don't have the capacities to make it work and I know only little about AHK and nearly nothing about HTML...
:eh:

Re: Uploading image link to Imgur

Posted: 22 Sep 2020, 20:14
by tmplinshi
Sorry, didn't read your question carefully.

try this:

Code: Select all

Msgbox % UploadToImgur(clipboard)

; Image can be a filename, base64 or URL
UploadToImgur(Image, ClientID := "fbf77ff49c42c8a")
{
	if FileExist(Image) {
		FileGetSize size, %Image% ; get file size in bytes
		PostData := ComObjArray(0x11, size) ; Create SAFEARRAY = VT_ARRAY|VT_UI1
		pvData := NumGet(ComObjValue(PostData) + 12 + (A_PtrSize==8 ? 4 : 0)) ; get pvData memeber
		FileOpen(Image, "r").RawRead(pvData + 0, size) ; read raw data
	} else {
		PostData := Image
	}

	whr := ComObjCreate("WinHttp.WinHttpRequest.5.1")
	whr.Open("POST", "https://api.imgur.com/3/image", true)
	whr.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded")
	whr.SetRequestHeader("Authorization", "Client-ID " ClientID)
	whr.Send(PostData)
	whr.WaitForResponse()

	if !RegExMatch(whr.ResponseText, """link"":""\K[^""]+", result) {
		RegExMatch(whr.ResponseText, """(message|error)"":""\K[^""]+", message)
		throw, message ? message : whr.ResponseText
	}
	return StrReplace(result, "\")
}

Re: Uploading image link to Imgur

Posted: 22 Sep 2020, 22:05
by SyntaxTerror
I am getting this error:
Image

Re: Uploading image link to Imgur

Posted: 22 Sep 2020, 22:19
by Jim Dunn
Did you copy an image to your clipboard before running the script?

I copied your avatar from this page to my clipboard (Right click - Copy image), ran the script, and the script uploaded it to: https://i.imgur.com/fSVsIJX.png

(note that it didn't seem to work for me from this page if I used 'Copy image address' or 'Copy image location' - I needed to copy the actual image to the clipboard, not its url -
copying image addresses (urls) on other pages such as the google logo from google.com did work though, so perhaps Imgur just didn't like the avatar urls from this site?
Running the script with https://www.autohotkey.com/boards/download/file.php?avatar=126101_1599011322.gif on the clipboard gives Error - File Type Invalid (1) )
Edit: I just tried that url manually at Imgur, and it doesn't like it: Sorry - url failed to upload - so it is Imgur rejecting it, not the script.

It also worked fine when I gave it a path to a test image of my avatar saved in a folder on my computer (in the first line of the script), like this:

Code: Select all

MsgBox % UploadToImgur("C:\Stuff\Testing\126101.gif")
The script uploaded that file to: https://i.imgur.com/oq6LS6w.gif

Re: Uploading image link to Imgur

Posted: 22 Sep 2020, 23:28
by SyntaxTerror
Mhhh... sorry the first time I tried I probably made a mistake in copying the link.

It seems to work, with the screenshot of the error message I posted above (original address: https://i.imgur.com/Jqskyxd.jpg), and some images from a Wikipedia page (https://upload.wikimedia.org/wikipedia/commons/thumb/b/b3/Wikipedia-logo-v2-en.svg/langfr-440px-Wikipedia-logo-v2-en.svg.png) and Commons (https://upload.wikimedia.org/wikipedia/commons/8/8c/English_Wikipedia_screenshot.png, but I don't know how to get the Imgur link (I cannot copy the text in the message box).
I'd like it to be pasted in a new or existing text file placed in the same folder as the script if possible, but I don't know with parameter to use.

Also, it is not working with my avatar (https://www.autohotkey.com/boards/download/file.php?avatar=78781_1495566606.png) or yours (Https://www.autohotkey.com/boards/download/file.php?avatar=126101_1599011322.gif), giving the same error message as above, but with "File type invalid (1)".

And when I am trying with another image, it shows this error (timeout):https://i.imgur.com/lFqg3Ns.jpg
and if I click yes (continue, it gives this error (data needed to terminate this process cannot be found): https://i.imgur.com/L5ddewk.jpeg

It also gives me the same "unkown error" as above if I try with a very long address taken on Google images.

:problem:

Re: Uploading image link to Imgur

Posted: 22 Sep 2020, 23:50
by Jim Dunn
Yeah - it seems Imgur is fussy, and doesn't like some kinds of url, as I discovered above - we can't really control that - so probably safest just to use (Right click - Copy Image) rather than (Right click - Copy Image address), or use a local file, as I showed above.


To save your Imgur urls to a text file in the directory from which you run the script, you can replace the first line of the script with these 3 lines:

Code: Select all

ImgurUrl := UploadToImgur(clipboard)
Msgbox % ImgurUrl
FileAppend, % ImgurUrl . "`n", % A_ScriptDir . "\ImgurUrls.txt"
Remove the MsgBox line if you don't want/need a pop up message.

Re: Uploading image link to Imgur  Topic is solved

Posted: 23 Sep 2020, 06:47
by teadrinker
SyntaxTerror wrote: Also, it is not working with my avatar (https://www.autohotkey.com/boards/download/file.php?avatar=78781_1495566606.png) or yours (Https://www.autohotkey.com/boards/download/file.php?avatar=126101_1599011322.gif), giving the same error message as above, but with "File type invalid (1)".
Try this:

Code: Select all

Msgbox % Clipboard := UploadToImgur("https://www.autohotkey.com/boards/download/file.php?avatar=78781_1495566606.png")

; Image can be a filename, base64, URL or SAFEARRAY = VT_ARRAY|VT_UI1
UploadToImgur(Image, clientID := "fbf77ff49c42c8a")
{
   Whr := ComObjCreate("WinHttp.WinHttpRequest.5.1")
   if FileExist(Image) {
      File := FileOpen(Image, "r")
      Image := ComObjArray(0x11, File.Length) ; Create SAFEARRAY = VT_ARRAY|VT_UI1
      File.RawRead(NumGet(ComObjValue(Image) + 8 + A_PtrSize), File.Length) ; read raw data
      File.Close()
   }
   else if RegExMatch(Image, "i)^https?://.+") {
      Whr.Open("GET", Image, true)
      Whr.Send()
      Whr.WaitForResponse()
      status := Whr.status
      if (status != 200)
         throw "Failed to get image data from URL, status: " . status
      contentType := Whr.GetResponseHeader("Content-Type")
      if !InStr(contentType, "image")
         throw "URL doesn't link to an image"
      Image := Whr.ResponseBody
   }
   Whr.Open("POST", "https://api.imgur.com/3/image", true)
   Whr.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded")
   Whr.SetRequestHeader("Authorization", "Client-ID " . clientID)
   Whr.Send(Image)
   Whr.WaitForResponse()
   response := Whr.ResponseText
   if !RegExMatch(response, """link"":""\K[^""]+", result) {
      RegExMatch(response, """(message|error)"":""\K[^""]+", message)
      throw message ? message : response
   }
   return StrReplace(result, "\")
}

Re: Uploading image link to Imgur

Posted: 26 Sep 2020, 23:38
by SyntaxTerror
teadrinker wrote:
23 Sep 2020, 06:47
Try this
Thanks teadrinker, it seems to work better.

I noticed that the Firefox extension Imgur-Uploader is also having problems with the same images.

Thank you both for your help, @Jim Dunn and @teadrinker. :thumbup:

Re: Uploading image link to Imgur

Posted: 26 Sep 2020, 23:46
by Jim Dunn
SyntaxTerror wrote:
26 Sep 2020, 23:38
teadrinker wrote:
23 Sep 2020, 06:47
Try this
I noticed that the Firefox extension Imgur-Uploader is also having problems with the same images.
They should implement teadrinker's improvements in their extension, then... ;)

Re: Uploading image link to Imgur

Posted: 26 Sep 2020, 23:52
by teadrinker
:wave:

Re: Uploading image link to Imgur

Posted: 04 Oct 2020, 23:37
by xjr
Also wanted to say thanks for this script,

Works fantastic for most images however when trying to upload a screenshot from the clipboard it throws the following :

https://imgur.com/a/00bLCZH

Any ideas or am i missing something?

Re: Uploading image link to Imgur

Posted: 05 Oct 2020, 04:56
by teadrinker
My code is not intended for uploading images from the clipboard, use this one.