[OpenSource] 一個基於 Azure Storage Blob 上面開發的圖片服務

2019-01-24


做網頁開發的人都知道,關於圖片這檔事其實說麻煩也不麻煩,但是就是瑣事,尤其是做電子商務的東西,客戶很喜歡上一些票票釀釀的圖,但是在做小圖的時候總是有點麻煩,因為可能客戶上傳 10240 x 7680 ,但是在列表的時候可能根據不同的 RWD 需求,要切成各種尺寸,不然就是用真男人的大絕招,全部都是讀取原圖,但是一張可能動輒 3 MB 以上,這樣一個網頁到底要撈取多少東西,之後我原本就有設計一套關於圖片的 Service 來 hub 網站上面所有的圖片跟動態切圖,但是去看 server 流量很大,雖然我都改成靜態的檔案但是流量還是大,而且備份的時候,覺得天啊 已經高達 100G 的圖檔,我真的瞬間崩潰…
最近接觸 Azure Storage Blob ,基本上他收費很便宜,不管是網路傳輸或是資料儲存,所以我就像說乾脆我把我原本的圖片服務儲存體搬到 Azure Storage Blob 上面,他有幾個好處,收費便宜看看計價表

是不是很便宜,接下來就是大概介紹
首先先去這邊下載原始碼 ,注意這是基於 .net Core 2.2 + Azure Blob ,所以你必須要有 .net Core 執行環境,然後 Azure 帳號。
佈署完成後,記得要修改 appsettings.json

{ "Logging": { "LogLevel": { "Default": "Warning" } }, "AllowedHosts": "*", "a9connesctionstring": "DefaultEndpointsProtocol=https;AccountName=YOUR_ACCOUNT_NAME;AccountKey=YOUR_ACCOUNT_KEY;EndpointSuffix=core.windows.net", "bloname": "n2imageagent", "uploadtoken": "your_token", "user_token_life_seconds": 90 }
a9connesctionstring : 您在 Azure 上面的 connection string
bloname : 所建立起來的 blob name (請注意,這邊 azure 那邊規定是全小寫,不可以有特殊符號)
uploadtoken : 使用者上傳需要給的 token
user_token_life_seconds : 使用者看到圖片,之後多久之後那張就會失效
接著 你就可以試著上傳圖片 到您的 server 上面去

C# Code for Upload

private string UploadImage(string file) { var src = System.IO.File.ReadAllBytes(file); Stream stream = new MemoryStream(src); HttpContent fileStreamContent = new StreamContent(stream); fileStreamContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data") { Name = "file", FileName = "xxx.jpg" }; fileStreamContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream"); using (var client = new HttpClient()) using (var formData = new MultipartFormDataContent()) { formData.Add(new StringContent("your_token"), "token"); formData.Add(new StringContent("測試"), "tag"); // 如果你指定filename 他就會覆蓋原本的圖片 // formData.Add(new StringContent("testgif"), "filename"); formData.Add(fileStreamContent, "file"); // Remember change your domain to https://yourdomain.com/api/upload to upload image. var response = client.PostAsync("https://yourdomain.com/api/upload", formData).Result; return response.Content.ReadAsStringAsync().Result; } } var result = UploadImage(AppDomain.CurrentDomain.BaseDirectory + "iphone7.jpg"); //response success //success:imageid //sample //success:01d1z45bm0nw8r4hfqcr6zbv26 //response error //error:error result //sample //error:token null

上傳成功後 你會拿到 success:圖片ID

可以透過
http://yourdomain.com/source/圖片ID 看到原圖

http://yourdomain.com/image/圖片ID/100 縮圖寬度到 100 px 高度按照比例變化
http://yourdomain.com/image/0/200 縮圖高度到 200 px 寬度按照比例變化
http://yourdomain.com/info/圖片ID 取得圖片的資訊

是不是,你就不用煩惱關於圖片的事情呢?
到這裡下載使用吧  https://github.com/donma/N2ImageAgent.AzureBlob
如果喜歡可以幫我按個星星嗎,感謝了 :)




當麻許的碎念筆記 2014 | Donma Hsu Design.