[C#] 可程式化的免費圖床方案 - imgbb

上一篇說到因為 imgur 因為客戶關係被鎖了,所以我就在繼續找其他可以用的免費圖床

上次介紹了一個有免費的圖床 - Cloudinary ,今天介紹另一家比較常見的 imgbb 

imgbb 有一個特色,你可以上傳一張圖片之後,指定他可以只存在一段時間,之後會自動消失,雖然我是不太會用到這功能

但是每個專案都有自己的玩法,或許你會用到,今天主要就是分享馬上貼上就可以用的程式碼

1. 申請 imgbb 帳號,之後 到這網址 https://api.imgbb.com/ 就可以拿到 api key 


2. 關於程式碼的部份,基本上我盡量就是用 .NET 內建的東西,包含解析 JSON 部份我也就是用 System.Text 裡面的,就不特別去用其他套件

C# code:
     

  var token="imgbb_api_key";
  var client = new HttpClient();
  //加入 expiration=600 就是代表十分鐘後自動消失,本案例沒有加上
  var requestUri = "https://api.imgbb.com/1/upload?key="+token;


       

  // 使用 MultipartFormDataContent 來構建 POST 請求
  using (var content = new MultipartFormDataContent())
  {
      byte[] fileBytes = File.ReadAllBytes(filePath);

      string base64String = Convert.ToBase64String(fileBytes);

      content.Add(new StringContent(base64String), "image");

      try
      {
          var response =  client.PostAsync(requestUri, content).Result;
          var responseContent =  response.Content.ReadAsStringAsync().Result;

          if (response.IsSuccessStatusCode)
          {
              return System.Text.Json.JsonDocument.Parse(responseContent).RootElement.GetProperty("data").GetProperty("url").ToString();
          }
          else
          {
              return null;
          }
      }
      catch (Exception ex)
      {
          throw ex;
      }
  }
  

/* Response JSON
{
  "data": {
    "id": "2ndCYJK",
    "title": "c1f64245afb2",
    "url_viewer": "https://ibb.co/2ndCYJK",
    "url": "https://i.ibb.co/w04Prt6/c1f64245afb2.gif",
    "display_url": "https://i.ibb.co/98W13PY/c1f64245afb2.gif",
    "width":"1",
    "height":"1",
    "size": "42",
    "time": "1552042565",
    "expiration":"0",
    "image": {
      "filename": "c1f64245afb2.gif",
      "name": "c1f64245afb2",
      "mime": "image/gif",
      "extension": "gif",
      "url": "https://i.ibb.co/w04Prt6/c1f64245afb2.gif",
    },
    "thumb": {
      "filename": "c1f64245afb2.gif",
      "name": "c1f64245afb2",
      "mime": "image/gif",
      "extension": "gif",
      "url": "https://i.ibb.co/2ndCYJK/c1f64245afb2.gif",
    },
    "medium": {
      "filename": "c1f64245afb2.gif",
      "name": "c1f64245afb2",
      "mime": "image/gif",
      "extension": "gif",
      "url": "https://i.ibb.co/98W13PY/c1f64245afb2.gif",
    },
    "delete_url": "https://ibb.co/2ndCYJK/670a7e48ddcb85ac340c717a41047e5c"
  },
  "success": true,
  "status": 200
}
*/
       
       
  

3. 小結論,網路上我查了一些文件,關於他的限制,就是限制檔案大小,還有會有些許不穩的狀況,目前是有客戶使用

會覺得比較慢 他的比較對象是 imgur ,這我就不得而知了,其實官方某種程度沒有提得很清楚關於免費帳戶的限制

所以如果你要使用,我給的建議是 記得備份一份到雲端,再來就是要使用 CDN 加速

先筆記到這吧,很簡單,主要就是介紹給大家有這服務

-

本文原文首發於我的個人部落格:可程式化的免費圖床方案 - imgbb

---

Yesterday I wrote down the code. I bet I could be your hero. I am a mighty little programmer.