tags:

views:

201

answers:

4

I'm going to be saving images into an SQL Database (don't know what type to use there), and I'm going to query the DB for an image of a students portrait shot.

What variable type should I use to store this image?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Nana_s_Student_Gradebook
{
    class Student
    {
        public string name { get; set; }
        public string lastName { get; set; }
        public byte[] picture { get; set; }
        public DateTime dateOfBirth { get; set; }
    }
}

Any guidance please? :)

+6  A: 

On the SQL Server side, by all means, use a VARBINARY(MAX) type - it's binary, it's up to 2 GB in size, it's fast, it's perfect for that use case. Up to an average image size of about 1 MB, this is probably your best bet - even better than using the SQL Server 2008 FILESTREAM attribute (which is great if you have lots of really really large images, larger than 1 MB on a regular basis; here, the binary file is itself stored in the server machine's file system under database control).

In your .NET code, you'll probably want to use Image or a derived classes - ultimately, you'll have to stream those bytes out to SQL Server one way or another, but you don't need to use a byte array from the beginning - all picture-related types in .NET offer some kind of streaming support.

marc_s
I'm creating my application using WPF; the using namespace should be: Using System.Drawing; right?
Serg
@Sergio: yes, the `Image` class is in System.Drawing.
marc_s
A: 

System.Drawing.Image or System.Drawing.Bitmap

Nick
Can you save these in a DB? Don't you have to save it to a byte[] somehow, first?
Jared Updike
Yes, I'd first have to change my image into a byte[] array before passing it along to my DB.
Serg
I was more concerned with the data structure you put up. Once you read the bytes from the database, I would use the Image.FromStream() method to read in the bytes (using a Memory stream or equivalent). For storing back to the DB, you can write the Image back to bytes. But for internal logic, I wouldn't carry around a byte array. Thats of limited use.
Nick
+1  A: 

You have it correct - use a byte array in your class. For images less than 1 MB, use a varbinary(max) column in SQL server. If the images are over 1 MB and you're using SQL Server 2008, consider using a FILESTREAM column.

You can use the chart on this MSDN page to refer to C#/Sql data type mappings.

womp
A: 

Consider storing the image as a file and then reference the filename in the DB, not the binary data itself. This has several advantages, such as allowing you to store images on other servers and reducing the load/traffic on the SQL server.

Steve Haigh