Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi i have a .aspx page in that page im using html image control and the image is in sql server so i have to fetch image and display in page
and code behind is vb.net in data base only two fields are available 'employeeid' and 'image' and image field data type is image
so plz help me frnds
Posted
Updated 30-Dec-11 20:01pm
v2
Comments
RaviRanjanKr 31-Dec-11 10:28am    
Please don't use short text words like plz instead of using Please :)

you can use image data on the filesystem and then simply store the url in the database. It would reduce the strain on the database.
new Image Generator in ASP.Net[^]
http://www.dotnettutorials.com/tutorials/database/save-retrieve-image-cs.aspx[^]
 
Share this answer
 
Try this: A generic Image-From-DB class for ASP.NET[^]

It's in C#, but that isn't a problem to convert (http://www.developerfusion.com/tools/convert/csharp-to-vb/[^] will probably do it) or use it as C# directly.
 
Share this answer
 
Step1:Insert Image in Table
Protected Sub btnInsert_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnInsert.Click
        'Make sure a file has been successfully uploaded
        If UploadedFile.PostedFile Is Nothing OrElse String.IsNullOrEmpty(UploadedFile.PostedFile.FileName) OrElse UploadedFile.PostedFile.InputStream Is Nothing Then
            Exit Sub
        End If

        'Make sure we are dealing with a JPG or GIF file
        Dim extension As String = Path.GetExtension(UploadedFile.PostedFile.FileName).ToLower()
        Dim MIMEType As String = Nothing

        Select Case extension
            Case ".gif"
                MIMEType = "image/gif"
            Case ".jpg", ".jpeg", ".jpe"
                MIMEType = "image/jpeg"
            Case ".png"
                MIMEType = "image/png"

            Case Else
                'Invalid file type uploaded
                Exit Sub
        End Select


        'Connect to the database and insert a new record into Products
        Using myConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("ImageGalleryConnectionString").ConnectionString)

            Const SQL As String = "INSERT INTO [Pictures] ([Title],[DateUploaded], [MIMEType], [ImageData]) VALUES (@Title,@DtUpload, @MIMEType, @ImageData)"
            Dim myCommand As New SqlCommand(SQL, myConnection)
            myCommand.Parameters.AddWithValue("@Title", PictureTitle.Text.Trim())
            myCommand.Parameters.AddWithValue("@DtUpload", DateTime.Now)
            myCommand.Parameters.AddWithValue("@MIMEType", MIMEType)

            'Load FileUpload's InputStream into Byte array
            Dim imageBytes(UploadedFile.PostedFile.InputStream.Length) As Byte
            UploadedFile.PostedFile.InputStream.Read(imageBytes, 0, imageBytes.Length)
            myCommand.Parameters.AddWithValue("@ImageData", imageBytes)

            myConnection.Open()
            myCommand.ExecuteNonQuery()
            myConnection.Close()
        End Using

    End Sub


Step 2: Get image from table and show on page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not (ListBox1.SelectedValue.Equals(String.Empty)) Then
            'Dim PictureID As Integer = Convert.ToInt32(Request.QueryString("PictureID"))
            Dim PictureID As Integer = Convert.ToInt32(ListBox1.SelectedValue)
            'Connect to the database and bring back the image contents & MIME type for the specified picture
            Using myConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("ImageGalleryConnectionString").ConnectionString)

                Const SQL As String = "SELECT [MIMEType], [ImageData] FROM [Pictures] WHERE [PictureID] = @PictureID"
                Dim myCommand As New SqlCommand(SQL, myConnection)
                myCommand.Parameters.AddWithValue("@PictureID", PictureID)

                myConnection.Open()
                Dim myReader As SqlDataReader = myCommand.ExecuteReader

                If myReader.Read Then
                    Response.ContentType = myReader("MIMEType").ToString()
                    Response.BinaryWrite(myReader("ImageData"))
                End If

                myReader.Close()
                myConnection.Close()
            End Using
        End If
    End Sub
 
Share this answer
 
v2
Comments
RaviRanjanKr 31-Dec-11 10:30am    
[Edited]Code is wrapped in "pre tag[/Edited]
XML
<%@ WebHandler Language="C#" Class="ImageFromDb" %>

using System;
using System.Web;
using System.Data.SqlClient;
/// <summary>
/// Read an image from the database and return it as a displayable image.
/// </summary>
public class ImageFromDb : IHttpHandler
    {
    /// <summary>
    /// Kept at class level to prevent needing to pass it through to private methods
    /// </summary>
    private HttpContext context = null;
    /// <summary>
    /// Interface property: Can another instance reuse this one?
    /// </summary>
    public bool IsReusable
        {
        get { return false; }
        }

    /// <summary>
    /// Reads an image from a database as returns it as a image.
    /// (For '[' read less-than, for ']' read greater-than)
    ///     [img alt="" src="ImageFromDb.ashx?db=myDB&table=myTable&field=myField&idName=idField&id=myID" /]
    /// </summary>
    /// <remarks>
    /// Parameters:
    ///    db    : name of database in connection strings - defaults to ImageDatabase
    ///    table : name of table in database containgin image field - defaults to myTable
    ///    field : name of field in table - defaults to image
    ///    idName: name of idField in table
    ///    id    : iD of record in table to extract image from
    /// </remarks>
    /// <param name="context"></param>
    public void ProcessRequest(HttpContext context)
        {
        this.context = context;
        // Read and default parameters
        string db = ReadOrDefault("db", "ImageDatabase");
        string table = ReadOrDefault("table", "myTable");
        string field = ReadOrDefault("field", "image");
        string idName = ReadOrDefault("idName", "id");
        string id = ReadOrDefault("id", "1");
        context.Response.ContentType = "image/JPEG";
        try
            {
            string dbCon = System.Configuration.ConfigurationManager.ConnectionStrings[db].ConnectionString;
            using (SqlConnection con = new SqlConnection(dbCon))
                {
                con.Open();
                string command = string.Format("SELECT {0} FROM {1} WHERE {2}=@ID", field, table, idName);
                SqlCommand com = new SqlCommand(command, con);
                com.Parameters.AddWithValue("@ID", id);
                object o = com.ExecuteScalar();
                if (o != null)
                    {
                    // Image found.
                    context.Response.BinaryWrite((byte[]) o);
                    }
                else
                    {
                    throw new ApplicationException("Requested ID is not in database");
                    }
                }
            }
        catch (Exception ex)
            {
            string err = string.Format("ImageFromDB?{0}&{1}&{2}&{3}&{4} failure", db, table, field, idName, id);
            SMWebSiteUtils.SMUtils.ErrorLog(err, ex.ToString());
            context.Response.WriteFile(@"~\Resources\Images\Problems\NoImageAvailable.png");
            }
        }
    /// <summary>
    /// Reads a value from the instance parameters, and returns it
    /// or the default if not specified.
    /// </summary>
    /// <param name="par">Parameter name to read</param>
    /// <param name="def">Defualt value if not specified</param>
    /// <returns>Parameter value or defualt if paramater not specified</returns>
    private string ReadOrDefault(string par, string def)
        {
        string val = context.Request.QueryString[par];
        if (string.IsNullOrEmpty(val))
            {
            val = def;
            }
        return val;
        }
    }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900