2010-03-14 43 views
3

我試圖發送圖像到Imgur的服務器。 一切都很順利,我從解析器獲取圖像的URL,但是當我試圖在Web瀏覽器上打開它時,我沒有得到圖像...只有一個「破碎的圖像」圖標。Imgur API和VB.NET的幫助 - 圖像POST

我認爲這是轉換爲字節數組的問題......但我不明白。請讓我知道/修復我的代碼。

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

這是在C#中Imgur API例如

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

要回答你的問題,你需要先閱讀圖像轉換成字節數組。然後將原始字節數組轉換爲Base64編碼字符串

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);