Managed C++: Read Image Data Using the ADO.NET DataReader, Page 2
Generic Method to Read Image Data
As promised, here's a generic method that takes as its parameters a data reader object pointer, a result set column index, and the name of a file. The function reads the data into memory and writes the image data to disk using the passed file name:
bool GetPictureValue(SqlDataReader* reader,
int columnIndex,
String* destination)
{
#pragma push_macro("new")
#undef new
bool success = false;
try
{
if (!reader->IsDBNull(columnIndex))
{
// Allocate a byte array
Byte image[] =
__gc new Byte[Convert::ToInt32((reader->GetBytes(columnIndex,
0, 0, 0,
Int32::MaxValue)))];
// Read the binary data into the byte array
reader->GetBytes(columnIndex, 0, image, 0, image->Length);
// Open FileStream and write buffer to file.
FileStream* stream = new FileStream(destination,
FileMode::Create,
FileAccess::Write);
stream->Write(image, 0, image->Length);
stream->Close();
success = true;
}
}
catch (Exception* e)
{
// handle exception
}
return success;
#pragma pop_macro("new")
}
Continuing with the Northwind Employees table example, you can now enumerate through every employee's photo data, writing the image data to disk with the following code:
SqlConnection* conn =
new SqlConnection(S"Server=localhost;"
S"Database=NorthWind;"
S"Integrated Security=true");
SqlCommand* cmd =
new SqlCommand(S"SELECT EmployeeID, Photo FROM Employees", conn);
conn->Open();
SqlDataReader* reader = cmd->ExecuteReader();
while (reader->Read())
{
String* fileName = String::Format(S"{0}.jpg", reader->Item[0]);
GetPictureValue(reader, 1, fileName);
}
conn->Close();
Note that the only columns read are the EmployeeID (as it's used to determine the file name) and the Photo column (containing the image data).
Looking Ahead
This article illustrated how the ADO.NET data reader class enables you to easily read image data from a database, and it presented a sample generic function for reading this data and writing it to a disk file. The next article will show how to write image data from a disk file to a database via the SqlParameter class.
About the Author
Tom Archer owns his own training company, Archer Consulting Group, which specializes in educating and mentoring .NET programmers and providing project management consulting. If you would like to find out how the Archer Consulting Group can help you reduce development costs, get your software to market faster, and increase product revenue, contact Tom through his Web site.
0 Comments (click to add your comment)
Networking Solutions
