Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Trouble converting Bitmap obejct to byte array for posting into DB

Status
Not open for further replies.

jasonsalas

IS-IT--Management
Jun 20, 2001
480
GU
Hi,

I'm trying to call a helper method that takes as an argument a Bitmap object, which needs to be converted to a byte array for posting into a database field of type IMAGE. Nothing fancy, the logic's just stumped me.

This is in in business tier, so it's not exactly using a file upload form, which 99% of the examples on the based on.

----------------------
private void SaveImageToDatabase(Bitmap bmp)
{
SqlConnection conn = new SqlConnection("conn_string");
SqlCommand comm = new SqlCommand("comm_string",conn);

// convert the image into a byte array
/* THIS IS THE PART I'M STUCK ON */
MemoryStream mem = new MemoryStream();
byte[] imageAsBits = new byte[mem.Length];
mem.Position = 0;
mem.Read(imageAsBits,0,imageAsBits.Length);

// add SqlParams here

conn.Open();
comm.ExecuteNonQuery();
conn.Close();

What's the proper way to save a Bitmap object as a byte[] so that it nay be used later in code? Thanks!
 
I'm hoping that this construct will work:

// convert the image into a byte array
Image img = Graphics.FromImage(bmp);
Image img2 = null;

MemoryStream mem = new MemoryStream();
img2.Save(mem,ImageFormat.Jpeg);
byte[] bits = mem.ToArray();

There's a helpful warning on why not to opt to save the byte[] to the same stream used to create the image:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top