How do I fetch a bmp from a BLOB and save it as a file?

  • Thread starter Thread starter Joakim Olesen
  • Start date Start date
J

Joakim Olesen

Hi

I have a table with a BLOB column which contains bmp images. I'm
unsuccessfully trying to fetch one of these images and saving it as a file.
The result is a file with a size of 12Kb, but it's not a valid BMP file (I
can't view it in an image viewer). The image I try to fetch is quite small
though, so the size (12Kb) is sensible. I've pasted my code below (and it
doesn't throw any exception):

using System;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Data;

namespace ConsoleApplication3
{
class Class1
{

[STAThread]
static void Main(string[] args)
{
SqlConnection Conn = new SqlConnection();
Conn.ConnectionString = "Here I put my connection string";
Conn.Open();

SqlCommand Comm = new SqlCommand("SELECT Picture FROM TableName WHERE
Name='John'", Conn);

BinaryWriter bw = new BinaryWriter(new FileStream(@"C:\Temp\Picture_" +
System.DateTime.Now.Hour.ToString() + "_" +
System.DateTime.Now.Minute.ToString() + "_" +
System.DateTime.Now.Second.ToString() + ".bmp", System.IO.FileMode.Create));
bw.Write((byte[])Comm.ExecuteScalar());
bw.Close();
Conn.Close();
}
}
}


I hope you can help me with this!

Joakim
 
Hi!
Try this:
reader = Comm.ExecuteReader();

if (reader.read())

{

System.IO.MemoryStream ms = new
System.IO.MemoryStream((byte[])reader["Scan"]);

Bitmap bm = new Bitmap(ms);

bm.Save(your_filename);

}



Hope that helps.

Best regards.
 
It turned out that my code was correct, but that the software that managed
the database automatically compressed the data in the BLOB column. After
disabling that compression, it worked fine.
 
Back
Top