今天碰到客戶有個需求, 要把某個網址的圖片抓回來並寫入DB, 最後前台從資料庫抓回並顯示
但DB的Schema存放的欄位是varchar(MAX)且不能更動
最後試成功的做法是將圖片抓回來轉成Base64String存進DB
程式碼如下:
Get image from url, convert to Base64String
HttpWebRequest lxRequest = (HttpWebRequest)WebRequest.Create(url);
String lsResponse = string.Empty;
using (HttpWebResponse lxResponse = (HttpWebResponse)lxRequest.GetResponse())
{
if (lxResponse.ContentType.ToUpper().StartsWith("IMAGE"))
{
using (BinaryReader reader = new BinaryReader(lxResponse.GetResponseStream()))
{
Byte[] lnByte = reader.ReadBytes((int)lxResponse.ContentLength);
string base64String = Convert.ToBase64String(lnByte);
}
}
}
Get image from upload file
if (httpPostedFileBase != null)
{
using (Stream inputStream = httpPostedFileBase.InputStream)
{
MemoryStream memoryStream = inputStream as MemoryStream;
if (memoryStream == null)
{
memoryStream = new MemoryStream();
inputStream.CopyTo(memoryStream);
}
Byte[] data = memoryStream.ToArray();
string base64String = Convert.ToBase64String(data);
}
}
讀寫的部分就以base64String就可以了
最後丟到View顯示的部分
<img srcset="@string.Format("data:image/png;base64,{0}", Model.base64String)" alt="" title="">