SiteMap  | About    

How to retrieve image from database

A .NET Data Provider implements the base System.Data classes to expose the objects, properties, methods, and events. SQL Server supplies a set of system data types that define all the types of data that can be used with SQL Server.

Image is a large object data type. Conversion of image data type to another data type is not supported, implicitly or explicitly. However, indirect conversion of image data can be performed.

  byte[] image = (byte[])command.ExecuteScalar();

The following C# source code shows how to retrieve an image from SQL Server.

using System;
using System.Data.SqlClient ;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace WindowsFormsApplication1
	public partial class Form1 : Form
		SqlConnection cnn ;
		string connectionString ;

		public Form1()

		private void button1_Click(object sender, EventArgs e)
			connectionString = "Data Source=servername; Initial Catalog=databasename; User ID=sa; Password=password";
			cnn = new SqlConnection(connectionString);

			MemoryStream stream = new MemoryStream();
			SqlCommand command = new SqlCommand("select img from imgtable where id=2", cnn);
			byte[] image = (byte[])command.ExecuteScalar();
			stream.Write(image, 0, image.Length);
			Bitmap bitmap = new Bitmap(stream);
			pictureBox1.Image = bitmap;
} (C) 2015    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.