Link to home
Start Free TrialLog in
Avatar of MCofer
MCofer

asked on

Retrive Taransparent PNG from Database

I am creating Png thumbnails with transparency and saving them to a SQL2008 database
When I retrieve them and display on an aspx web page the background is black.
The priginal thumb written to a file display correctly;

Saving to file 
image = new Bitmap(photoSpec);
            photo.Thumb = (Bitmap)GetThumbnail(image, 140);
            if (!Directory.Exists(thumbDir))
                Directory.CreateDirectory(thumbDir);
            photo.Thumb.Save(thumbDir + photo.PhotoId + ".PNG", ImageFormat.Png);
 
 
Writing To DB
ms = new MemoryStream();
_thumb.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] thumbBytes = ms.GetBuffer();
_thumb.Dispose();
ms.Close();
sqlString = new StringBuilder();
sqlString.AppendFormat("INSERT INTO Images(ImageId,  Thumb)");
sqlString.AppendFormat(" VALUES(@ImageId,  @Thumb) ");
using (SqlCommand sqlCommand = new SqlCommand(sqlString.ToString(), sqlConn))
{
    sqlCommand.Parameters.AddWithValue("@ImageId", _photoId);
    sqlCommand.Parameters.AddWithValue("@Thumb", thumbBytes);
    sqlCommand.ExecuteScalar();
}
 
Reading from DB
string sqlString = "SELECT Thumb FROM Images WHERE ImageId = @IMAGE_ID";
            using (SqlCommand sqlCommand = new SqlCommand(sqlString.ToString(), sqlConn))
            {
                sqlCommand.CommandType = CommandType.Text;
                sqlCommand.Parameters.AddWithValue("@IMAGE_ID", theID);
                object thumb = (byte[])sqlCommand.ExecuteScalar();      
            }
 
 
Displaying
  MemoryStream ms = new MemoryStream(thumb);
 Image img = Image.FromStream(ms);
 using (MemoryStream stmMemory = new MemoryStream())
{
            context.Response.Clear();
            context.Response.ContentType = "image/png";
            img.Save(stmMemory, System.Drawing.Imaging.ImageFormat.Png);
            stmMemory.WriteTo(context.Response.OutputStream);
            context.Response.End();
        }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Member_2_4694817
Member_2_4694817

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial