c#資料庫存取圖片的方式

來源:互聯網
上載者:User

 

第一種方式   檔案夾與資料庫配合

        近來做了不少關於這塊的功能 ,隨著網路的飛速發展,網路存取圖片已不再是神話,而成為了一種時尚,如果是你 是用Asp.net開發的話,可能更多的人會考慮使用資料庫儲存圖片的路經,而在檔案夾是儲存圖片的方式。這種方式主要的方法有兩個一個就是怎麼樣讀取圖片,怎麼樣儲存圖上,讀取的話我就不多說的這個是最簡單的了,只要大家把地址=給儲存圖片的對象就行了,在取的時候一般要使用相對位址也就是“~” 如下所示

ImageUrl="../CardDeal/SellCardZhi.jpg' ImageUrl="~/CardDeal/SellCardZhi.jpg' 

 

當然這前面要加上你自己的圖片所在伺服器的檔案夾的名稱

我們來看是一下是怎麼儲存的吧,我常用的一個方法是這樣的

/// <summary>    /// 上傳圖片    /// </summary>    /// <param name="FUSShopURL">FileUpload對象</param>    /// <param name="UpladURL">圖片要放到的目錄名稱</param>    /// <returns>如果FileUpload不為空白則返回上傳後的圖片位置,否則返回為空白字元</returns>    public  static  string  uploadImage(FileUpload FUSShopURL, string UpladURL)    {        if (FUSShopURL.HasFile)        {            //擷取當前的時間,一當作圖片的名字            string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + DateTime.Now.Millisecond.ToString();            //擷取圖片的副檔名            string Extent = System.IO.Path.GetExtension(FUSShopURL.PostedFile.FileName);            //重新命名圖片            fileName += Extent;            //設定上傳圖片儲存的檔案夾            string dir = System.Web.HttpContext.Current.Server.MapPath(UpladURL);            //指定圖片的路徑及檔案名稱            string path = dir + "\\" + fileName;            //把上傳得圖片儲存到指定的檔案加中            FUSShopURL.PostedFile.SaveAs(path);            return  fileName;        }        else        {            return "";        }    }

 

這個方法是與FileUpload控制項 一起使用的,方法很簡單大家一看就明白了。

方法返回的就是一個相對的路經可以直接儲存的資料裡,然後從前台調用就可以了

 

第二種方式    直接把圖片的Base64String碼進行存取

 

 

          這種方法很方便,直接轉化一下就行了,不需要書寫很麻煩的路經問題

先看一下是怎麼儲存到資料庫的吧

 

//選擇圖片        private void button1_Click(object sender, EventArgs e)        {            OpenFileDialog openfile = new OpenFileDialog();            openfile.Title = "請選擇用戶端longin的圖片";            openfile.Filter = "Login圖片(*.jpg;*.bmp;*png)|*.jpeg;*.jpg;*.bmp;*.png|AllFiles(*.*)|*.*";            if (DialogResult.OK == openfile.ShowDialog())            {                try                {                    Bitmap bmp = new Bitmap(openfile.FileName);                    pictureBox1.Image = bmp;                    pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;                    MemoryStream ms = new MemoryStream();                    bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);                    byte[] arr = new byte[ms.Length];                    ms.Position = 0;                    ms.Read(arr, 0, (int)ms.Length);                    ms.Close();                    //直接返這個值放到資料就行了                    pic = Convert.ToBase64String(arr);                }                catch { }            }        }

 

   讀取的方法也很簡單, pic就是我們得到的圖片字串只要我們儲存到資料庫裡,從下面的方法裡讀取就可以了

需要注意的地方我都加的有注釋

 

//載入圖片        private void Form1_Load(object sender, EventArgs e)        {            try            {               // pic=........這一句換成從資料庫裡讀取就可以了                //判斷是否為空白,為空白時的不執行                if (!string.IsNullOrEmpty(pic))                {                    //直接返Base64碼轉成數組                    byte[] imageBytes = Convert.FromBase64String(pic);                    //讀入MemoryStream對象                    MemoryStream memoryStream = new MemoryStream(imageBytes, 0, imageBytes.Length);                    memoryStream.Write(imageBytes, 0, imageBytes.Length);                    //轉成圖片                    Image image = Image.FromStream(memoryStream);                    //memoryStream.Close();//不要加上這一句否則就不對了                    // 將圖片放置在 PictureBox 中                    this.pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;                    this.pictureBox1.Image = image;                }            }            catch { }        }

大家看一下效果吧

在這裡我們只要單擊選擇圖片直接就可以更換。這些很簡單但是我個人感覺還是很常用的,而且網上關於這塊的例子著實不少,不過真正能幫上忙的還真不多,因為我們的好幾個項目裡用到了這些方法,或多或少的還是有些員工不怎麼會, 在這裡貼一貼方便新手查看吧。呵呵

下面的本例子的所有代碼

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.IO;using System.Threading;namespace WindowsFormsApplication1{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        string pic = "";        //載入圖片        private void Form1_Load(object sender, EventArgs e)        {            try            {                if (!string.IsNullOrEmpty(pic))                {                    byte[] imageBytes = Convert.FromBase64String(pic);                    MemoryStream memoryStream = new MemoryStream(imageBytes, 0, imageBytes.Length);                    memoryStream.Write(imageBytes, 0, imageBytes.Length);                    Image image = Image.FromStream(memoryStream);                    // 將圖片放置在 PictureBox 中                    this.pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;                    this.pictureBox1.Image = image;                }            }            catch { }        }        //選擇圖片        private void button1_Click(object sender, EventArgs e)        {            OpenFileDialog openfile = new OpenFileDialog();            openfile.Title = "請選擇用戶端longin的圖片";            openfile.Filter = "Login圖片(*.jpg;*.bmp;*png)|*.jpeg;*.jpg;*.bmp;*.png|AllFiles(*.*)|*.*";            if (DialogResult.OK == openfile.ShowDialog())            {                try                {                    Bitmap bmp = new Bitmap(openfile.FileName);                    pictureBox1.Image = bmp;                    pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;                    MemoryStream ms = new MemoryStream();                    bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);                    byte[] arr = new byte[ms.Length];                    ms.Position = 0;                    ms.Read(arr, 0, (int)ms.Length);                    ms.Close();                    pic = Convert.ToBase64String(arr);                }                catch { }            }        }    }}

 

第三種方式   讀成二進位後進行存取

 

 

 

   先把圖片讀成二進位以後再做處理,這樣快捷而且代碼相對少很多,還有就是感謝下面幾位網友的提醒和建議,在這裡我把我簡單寫的代碼貼一下,怎麼樣儲存到資料庫的方法還是大家自己寫我只提供存取的方法

 private void button1_Click(object sender, EventArgs e)        {            OpenFileDialog openfile = new OpenFileDialog();            openfile.Title = "請選擇用戶端longin的圖片";            openfile.Filter = "Login圖片(*.jpg;*.bmp;*png)|*.jpeg;*.jpg;*.bmp;*.png|AllFiles(*.*)|*.*";            if (DialogResult.OK == openfile.ShowDialog())            {                try                {                    //讀成二進位                    byte[] bytes = File.ReadAllBytes(openfile.FileName);                    //直接返這個儲存到資料就行了cmd.Parameters.Add("@image", SqlDbType.Image).Value = bytes;                    //輸出二進位  在這裡把資料中取到的值放在這裡byte[] bytes=(byte[])model.image;                    pictureBox1.Image = System.Drawing.Image.FromStream(new MemoryStream(bytes));                    this.pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;                    // 如果儲存成檔案:                    File.WriteAllBytes(@"d:\text.jpg", bytes);                }                catch { }            }        }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.