Reputation: 51
I have an bitmap in System.Drawing. I know it must be converted to a byte[] to be stored in my table.
My table field:
public class Task
public byte? TaskImage { get; set; }
I have this in line code so far:
MemoryStream ms = new MemoryStream();
mybmp.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
Task.TaskImage =
db.SaveChanges();
I've been referenced to this:
public static byte[] ImageToByteArray(Image image)
{
var memoryStream = new MemoryStream();
image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg); // consider format
return memoryStream.ToArray();
}
but can't figure out how to apply it. This attempt doesn't work.
Task.TaskImage = Image.FromStream(ms.ToArray())
Can someone provide the code to go from the System.Drawing to Task.TaskImage= in inline code, or how to reference the function ImageToByteArray(Image image) in my code? In my MVC project, where is the proper place to put this function ImageToByteArray(Image image) if used?
Upvotes: 0
Views: 769
Reputation: 16358
You're on the right track.
One mistake I see is that
public byte? TaskImage { get; set; }
Needs to be a byte array. That is only a single nullable byte. Change it to
public byte[] TaskImage { get; set; }
In it's simplest form, an image is just a series of bits that are organised in a particular way (like any virtual object stored on a computer).
Databases aren't very good at storing complex types of data; they typically store strings (varchar, for example), integers of various sizes, floating point numbers, boolean values (a bit) and so on. In order to store something complex like an image we have to split the image up in to bytes and give that to the database (they can handle bytes (groups of bits) easily). You seem to know all of this.
In order to save an image to the database we need to know what format it's in and we need to be able to read all the bytes of the image.
Streams (What is a stream?) are useful here. They allow us to read and write a sequence of bytes. .NET classes like Image may also be useful for loading information about an image.
Suppose we have an image stored as a byte array in a database. Entity Framework loads the object for us as a Task
object.
public class Task
{
public byte[] TaskImage { get; set; }
}
To load the image:
Task task;
var ms = new MemoryStream(task.TaskImage);
Image img = Image.FromStream(ms);
Or
Bitmap bmp = new Bitmap(ms);
Task task = new Task();
MemoryStream ms = new MemoryStream();
Image img = Image.FromFile("...");
img.Save(ms, img.RawFormat);
ms.Position = 0;
task.TaskImage = new byte[ms.Length];
ms.Read(TaskImage, 0, (int)ms.Length);
dbContext.Tasks.Add(task);
dbContext.SaveChanges();
Upvotes: 1