2012-03-10 99 views
2

我需要插入圖像我本地使用SQL。什麼樣的數據類型用於保存數據庫中的圖像

我做這樣說:

CREATE TABLE [dbo].[Table_1](
     [SelectedImages] [image] NOT NULL, 
     [Path] [ntext] NOT NULL 
) 

to add an image, do this: 

INSERT INTO [testing].[dbo].[Table_1] 
      ([SelectedImages] 
      ,[Path]) 
    VALUES 
      ('D:\desktop\05022006\free_chart1.gif' ,'D:\desktop\05022006\free_chart1.gif') 

的問題是我需要事後檢索圖像...

我使用Telerik的控制顯示存儲爲二進制數據的圖像數據庫 而且我不知道類型爲「圖像」,因爲它正確的一個不工作...

    <telerik:RadBinaryImage runat="server" ID="RadBinaryImage1" DataValue='<%#Eval("Photo") %>' 
         AutoAdjustImageControlSize="false" Width="90px" Height="110px" ToolTip='<%#Eval("ContactName", "Photo of {0}") %>' 
         AlternateText='<%#Eval("ContactName", "Photo of {0}") %>' /> 

什麼樣的數據類型的你們怎麼用它來存儲一個我法師? 在此先感謝

+1

您是否必須將圖像存儲在數據庫中?您可以將路徑存儲到圖像的保存位置。否則,請參閱http://stackoverflow.com/questions/335342/using-sql-server-as-image-store。請注意,未來將不再支持圖像:http://msdn.microsoft.com/en-us/library/ms187993.aspx – dash 2012-03-10 20:22:39

回答

3

您可以使用圖像類型將圖像存儲在數據庫中,就像您在問題中定義的一樣。但是,您需要先將圖像轉換爲字節數組。

string path = "D:\\desktop\\05022006\\free_chart1.gif" 
using (System.IO.FileStream fstream = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read)) 
{ 
    // Create a buffer to hold the stream of bytes 
    byte[] buffer = new byte[fstream.Length]; 
    // Read the bytes from this stream and put it into the image buffer 
    fstream.Read(buffer, 0, (int)fstream.Length); 
    fstream.Close(); 
    //now you can insert buffer into the database 
} 

當您想要從數據庫中檢索圖像時,必須將其從byte []轉換回來。

if (byteArray != null) 
{ 
    if (byteArray.Length > 0) 
    { 
    // Create a new MemoryStream and write all the information from the byte array into the stream 
    using (System.IO.MemoryStream ms = new System.IO.MemoryStream(byteArray, true)) 
    { 
     ms.Write(byteArray, 0, byteArray.Length); 

     // Use the MemoryStream to create the new BitMap object 
     Bitmap photo = new Bitmap(ms); 

     ms.Close(); 

     //now you can use photo 
    } 
    } 
} 
2

什麼樣的數據類型的你們怎麼用它來存儲圖像?

  1. 它取決於形勢&其呼叫。

  2. 有時候,只是存儲圖像的URL一個VARCHAR領域內將 足夠'C:/Data/UserName/uploads/myGuid+filename.jpg' &實際文件存在於磁盤(事務管理很難用這種方法,但非常適用於小型的要求)

  3. 當事務管理當務之急,你可以在數據庫裏面將它們存儲在VARBINARY(最大值)字段Storing images in SQL Server
  4. 的SQL Server FILESTREAM也與最新的SQLServer的一個選項,在該文件存儲在文件系統中的數據庫管理SQL Server filestream Overview
相關問題