C# .NET - display the image from database

Asked By Deepika S
11-Feb-12 07:10 AM
how retrieve the image from sql database
  Sreekumar P replied to Deepika S
11-Feb-12 07:37 AM
Hi,

Getting and displaying an image with C# is actually considerably easier than putting the image into SQL Server. Basically, all we do is write the image's binary stream to the web page. And here's a bonus: The scripts not only display the images, but resize them! This technique is great for eCommerce sites; you can show thumbnails for product images; the thumbnail blows up into the full-size image only when the user clicks the thumbnail.

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Data;
using System.Data.SqlClient;
 
namespace ImageResizing
{
 
  public class MainDisplay : System.Web.UI.Page
  {
 
    public void Page_Load(System.Object sender, System.EventArgs e)
    {
 
      try
      {
 
        System.Int32 _ImgID = System.Convert.ToInt32(Request.QueryString["ImgID"]);
 
        System.Int32 _height = System.Convert.ToInt32(Request.QueryString["height"]);
 
        System.Int32 _width = System.Convert.ToInt32(Request.QueryString["width"]);
 
        System.Data.SqlClient.SqlConnection Con = new System.Data.SqlClient.SqlConnection("Data Source=216.221.103.167;database=e-commerce;uid=webappsx;pwd=tyqldf");
 
        System.String SqlCmd = "SELECT * FROM Image WHERE img_pk = @ImageID";
 
        System.Data.SqlClient.SqlCommand SqlCmdObj = new System.Data.SqlClient.SqlCommand(SqlCmd, Con);
 
        SqlCmdObj.Parameters.Add("@ImageID", System.Data.SqlDbType.Int).Value = _ImgID;
 
        Con.Open();
 
        System.Data.SqlClient.SqlDataReader SqlReader = SqlCmdObj.ExecuteReader();
 
        SqlReader.Read();
 
        System.Web.HttpContext.Current.Response.ContentType = "image/jpeg";
 
        System.Drawing.Image _image = System.Drawing.Image.FromStream(new System.IO.MemoryStream((byte[])SqlReader["img_data"]));
 
        System.Drawing.Image _newimage = _image.GetThumbnailImage(_width, _height, null, new System.IntPtr());
 
        _newimage.Save(System.Web.HttpContext.Current.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
 
      }
      catch (System.Exception Ex)
      {
 
        System.Web.HttpContext.Current.Trace.Write(Ex.Message.ToString());
 
      }
 
    }
 
  }
 
}



I recommend reviewing the System.Drawing namespace in some detail. Not only can it resize images, but make them transparent or crop them, among other things.
  dipa ahuja replied to Deepika S
11-Feb-12 07:58 AM
► Store
private void btnupload_Click(object sender, EventArgs e)
{
  try
  {
    openFileDialog1.ShowDialog(this);
    openFileDialog1.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";
        
    byte[] image;
 
    string strFn=openFileDialog1.FileName;
 
    FileStream fs = new FileStream(strFn, FileMode.Open);
    BinaryReader reader = new BinaryReader(fs);
    image = reader.ReadBytes((int)fs.Length);
    fs.Close();
 
    OleDbConnection conn = new OleDbConnection("ConnectionString");
    conn.Open();
    string query = "Insert into pictures (name,images) values(@name,@images)";
 
    OleDbCommand comm = new OleDbCommand(query, conn);
    comm.Parameters.AddWithValue("name", Path.GetFileName(strFn).ToString());
 
    comm.Parameters.AddWithValue("images", image);
 
    comm.ExecuteNonQuery();
    MessageBox.Show("Record Added");
 
    conn.Close();
    bind();
    pictureBox1.Image = new Bitmap(strFn);        
  }
  catch (Exception)
  {
    throw new ApplicationException("Failed loading image");
  }     
}
 
► display
private void button1_Click(object sender, EventArgs e)
{
  OleDbConnection conn = new OleDbConnection(Program.c);
      
  OleDbDataAdapter da=new OleDbDataAdapter("Select images from pictures",conn);
      
  DataTable dt = new DataTable();
  da.Fill(dt);
      
  conn.Open();
  //display 1st image
  if (dt.Rows.Count > 0)
  {
    byte[] storedImage = (byte[])dt.Rows[0]["images"];
    Image newImage;
 
    MemoryStream stream = new MemoryStream(storedImage);
    newImage = Image.FromStream(stream);
 
    pictureBox1.Image = newImage;
  }        
}
 
 
 
 
  kalpana aparnathi replied to Deepika S
11-Feb-12 12:58 PM
hi,

http://www.dotnettutorials.com/tutorials/database/save-retrieve-image-cs.aspx to retrieve image from database with understable code

Thanks,
Create New Account
help
Rolllup option on OleDbDataAdapter SQL Server I don't know if Sql Server would give me the same error, but I am running a statement that I assume statement works fine if I don't have the "with Rollup" option. da2 = New OleDb.OleDbDataAdapter("Select F1, F2, F3, F4, F5, Sum(F6) from " & TextBox4.Text & " where F6 <> '0' Group I get the error: Syntax error with owneraccess option What is causing that? Thanks, Tom SQL Server Programming Discussions SQL Server (1) Hi Tom, Try split the statement into two so you
import excel sheet into a sql server table .NET Framework hi! I am trying to create a sql server table from an excel sheet. Here is the code I have: 'This procedure the xlsx file and dumps it to a table in SQL Server Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5 String = excelConnection.Open() Dim excelCommand As New System.Data.OleDb.OleDbCommand("SELECT * INTO [ODBC; Driver = {SQL Server};Server = " & lstServers.SelectedValue & ";Database = SpamBank;Trusted_Connection = yes].[temp_spaminfo] FROM [Sheet1$];", excelConnection) Dim conn As SqlConnection
uploading excel data to sql server tables Hi all, I am using sql server 2005 , asp.net2.0 , C#. I want to upload data from excel to sql server tables. In the end if all data uploded then delete all rows in excel else Dim sExcelFileName As String Dim sWorkbook As String 'Create our connection string sSQLTable = "dbo.tblStrength" '<- - sql table to write to sExcelFileName = "~ \ data_drop \ strength \ Strength.xls" '<- -location of file to import sWorkbook followed by $ sign Dim sExcelConnectionString As String = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = " & Server.MapPath(sExcelFileName) & ";Extended Properties = ""Excel 8.0;HDR = YES;""" Dim sSqlConnectionString As String = ConfigurationManager.ConnectionStrings
Copy data from SQL Server to MS Access I want to copy data from one table in a SQL server database to another table in MS Access database, through vb.net code. For that I of the destination table (Ms Access - String format) 2. The name of the source table (SQL Server - String format) Now in the sub what I have done is the following 'The following Sub is used to copy data from the sql server to access database Private Sub CopyData(ByVal source_table As String, ByVal dest_table As String, ByVal
I want know how to import excel sheet data into databse using stored procedure in sql server Use this - INSERT Personal (Name, ID) SELECT Name, ID FROM OPENROWSET('MSDASQL', 'Driver = {Microsoft Excel hi. . Follow this link . . http: / / www.aspsnippets.com / Articles / Read-and-Import-Excel-Sheet-into-SQL-Server-Database-in-ASP.Net.aspx HI try htis Stored Procedures For this article I have SheetName varchar ( 20 ), @FilePath varchar ( 100 ), @HDR varchar ( 3 ), @TableName varchar ( 50 ) AS BEGIN DECLARE @SQL nvarchar ( 1000 ) IF OBJECT_ID ( @TableName , 'U' ) IS NOT NULL SET @SQL = 'INSERT INTO ' + @TableName + ' SELECT * FROM OPENDATASOURCE' ELSE SET @SQL = 'SELECT * INTO ' + @TableName + ' FROM OPENDATASOURCE' SET @SQL = @SQL + '(''Microsoft.Jet.OLEDB.4.0'', ''Data Source = ' SET @SQL = @SQL + @FilePath + ';Extended Properties = ''''Excel