Help with Imgur API and VB.NET - Image POST

点点圈 提交于 2021-02-18 17:09:29

问题


I'm trying to send an image to Imgur's server. Everything went fine and I'm getting the URL of the image from the parser but when I'm trying to open it on the web browser, I'm not getting the image... only a "broken image" icon.

I think it's a problem in the convertion to the byte array.... but I don't get it. please let me know/fix my code.

   Dim image As Image = image.FromFile(OpenFile.FileName)
    Dim ms As New MemoryStream()
    ' Convert Image to byte[]
    image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
    Dim imageBytes As Byte() = ms.ToArray()
    Dim wb As WebRequest = WebRequest.Create(New Uri("http://imgur.com/api/upload.xml"))
    wb.ContentType = "application/x-www-form-urlencoded"
    wb.Method = "POST"
    wb.Timeout = 10000
    Console.WriteLine(imageBytes.Length)
    Dim parameters As String = "key=a801fa0b08a2117f5bb62b006f769b99&image=" + Convert.ToBase64String(imageBytes)
    Dim encoding As New System.Text.UTF8Encoding()
    Dim bytes As Byte() = encoding.GetBytes(parameters)
    Dim os As System.IO.Stream = Nothing
    Try
        wb.ContentLength = bytes.Length
        os = wb.GetRequestStream()
        os.Write(bytes, 0, bytes.Length)
        Dim xmlData As String = POSThandling.makePOSTrequest("http://imgur.com/api/upload.xml", New String() {parameters})
        Dim xmlDoc As XmlDocument = New XmlDocument()
        xmlDoc.LoadXml(xmlData)
        Dim name As XmlNodeList = xmlDoc.GetElementsByTagName("original_image")
        Dim imageText As String = (name(0).InnerText).ToString
        messageText.Text = imageText.ToString
        PanelUpload.Visible = False
        UpImage.Enabled = True
        SendMsg.Enabled = True
    Finally
        If Not (os Is Nothing) Then
        End If
    End Try

回答1:


Here is the Imgur API example in C#

http://api.imgur.com/examples#uploading_cs

To answer your question, you need to first read the image into an array of bytes. Then convert the raw byte array into a Base64 encoded string

FileStream fileStream = File.OpenRead(imageFilePath);
byte[] imageData = new byte[fileStream.Length];
fileStream.Read(imageData, 0, imageData.Length);
fileStream.Close();
string base64EncodedImage = System.Convert.ToBase64String(imageData);


来源:https://stackoverflow.com/questions/2443172/help-with-imgur-api-and-vb-net-image-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!