Click here to Skip to main content
15,949,686 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to convert image to stream and pass it as parameter to other function please help me with this...
thanks in advance
Posted

public Image GetImageById( int id )
{
// Initialize connection.
SqlConnection dbconn = new SqlConnection( "connectionstring" );

try
{
// Create command and fetch image.
using(SqlCommand command = dbconn.CreateCommand())
{
// Set select query and add Id parameter with value.
command.CommandText = "SELECT [ImageField] FROM [Table1] WHERE [Id] = @Id";
command.Parameters.Add("@Id", SqlDbType.Int, 4).Value = id;

// Open the connection.
dbconn.Open();

// Excecute the select query.
byte[] imageData = (byte[])command.ExecuteScalar();

// If we recieved an image, return it; otherwise
// just return a null reference value.
if( imageData != null && imageData.Lenght != 0 )
{
using(MemoryStream stream = new MemoryStream( imageData ))
{
return Image.FromStream( stream );
}
}
else
{
// Image not found.
return null;
}
}
}
finally
{
dbconn.Close();
}
}
 
Share this answer
 
Hi,

Have a look here:
http://stackoverflow.com/a/1668493[^]
 
Share this answer
 
C#
public Image GetImageById( int id )
{
    // Initialize connection.
    SqlConnection dbconn = new SqlConnection( "connectionstring" );

    try
    {
        // Create command and fetch image.
        using(SqlCommand command = dbconn.CreateCommand())
        {
            // Set select query and add Id parameter with value.
            command.CommandText = "SELECT [ImageField] FROM [Table1] WHERE [Id] = @Id";
            command.Parameters.Add("@Id", SqlDbType.Int, 4).Value = id;
            
            // Open the connection.
            dbconn.Open();
            
            // Excecute the select query.
            byte[] imageData = (byte[])command.ExecuteScalar();
            
            // If we recieved an image, return it; otherwise
            // just return a null reference value.
            if( imageData != null && imageData.Lenght != 0 )
            {            
                using(MemoryStream stream = new MemoryStream( imageData ))
                {
                    return Image.FromStream( stream );
                }
            }
            else
            {
                // Image not found.
                return null;
            }
        }
    }
    finally
    {
        dbconn.Close();
    }
}
 
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