我想以匿名用户的身份使用它的 API 将图像上传到 Imgur.com。上传图片后,我想动态获取该图片网址。我如何使用 C# Winforms 实现这一点?
问问题
1433 次
1 回答
1
该文档提供了一个您可以尝试的示例:
using System;
using System.IO;
using System.Net;
using System.Text;
namespace ImgurExample
{
class Program
{
static void Main(string[] args)
{
PostToImgur(@"C:\Users\ashwin\Desktop\image.jpg", IMGUR_ANONYMOUS_API_KEY);
}
public static void PostToImgur(string imagFilePath, string apiKey)
{
byte[] imageData;
FileStream fileStream = File.OpenRead(imagFilePath);
imageData = new byte[fileStream.Length];
fileStream.Read(imageData, 0, imageData.Length);
fileStream.Close();
const int MAX_URI_LENGTH = 32766;
string base64img = System.Convert.ToBase64String(imageData);
StringBuilder sb = new StringBuilder();
for(int i = 0; i < base64img.Length; i += MAX_URI_LENGTH) {
sb.Append(Uri.EscapeDataString(base64img.Substring(i, Math.Min(MAX_URI_LENGTH, base64img.Length - i))));
}
string uploadRequestString = "image=" + sb.ToString() + "&key=" + imgurApiKey;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://api.imgur.com/2/upload");
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ServicePoint.Expect100Continue = false;
StreamWriter streamWriter = new StreamWriter(webRequest.GetRequestStream());
streamWriter.Write(uploadRequestString);
streamWriter.Close();
WebResponse response = webRequest.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(responseStream);
string responseString = responseReader.ReadToEnd();
}
}
}
服务器返回的响应将包含指向上传图像的链接。例如:
{
"upload": {
"image": {
"name": false,
"title": "",
"caption": "",
"hash": "cSNjk",
"deletehash": "ZnKGru1reZKoabU",
"datetime": "2010-08-16 22:43:22",
"type": "image\/jpeg",
"animated": "false",
"width": 720,
"height": 540,
"size": 46174,
"views": 0,
"bandwidth": 0
},
"links": {
"original": "http:\/\/imgur.com\/cSNjk.jpg",
"imgur_page": "http:\/\/imgur.com\/cSNjk",
"delete_page": "http:\/\/imgur.com\/delete\/ZnKGru1reZKoabU",
"small_square": "http:\/\/imgur.com\/cSNjks.jpg",
"large_thumbnail": "http:\/\/imgur.com\/cSNjkl.jpg"
}
}
}
为了使用匿名 API,您需要获取 API 密钥。
于 2012-08-03T08:43:19.550 回答