Basically I am inserting an image using the listviews inserting event, trying to resize an image from the fileupload control, and then save it in a SQL database using LINQ.
I found some code to create a new bitmap of the content in the fileupload control, but this was to store it in a file on the server, from this source, but I need to save the bitmap back into the SQL database, which I think I need to convert back into a byte[] format.
So how do I convert the bitmap to a byte[] format?
If I am going about this the wrong way I would be grateful it you could correct me.
Here is my code:
// Find the fileUpload control
string filename = uplImage.FileName;
// Create a bitmap in memory of the content of the fileUpload control
Bitmap originalBMP = new Bitmap(uplImage.FileContent);
// Calculate the new image dimensions
int origWidth = originalBMP.Width;
int origHeight = originalBMP.Height;
int sngRatio = origWidth / origHeight;
int newWidth = 100;
int newHeight = sngRatio * newWidth;
// Create a new bitmap which will hold the previous resized bitmap
Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);
// Create a graphic based on the new bitmap
Graphics oGraphics = Graphics.FromImage(newBMP);
// Set the properties for the new graphic file
oGraphics.SmoothingMode = SmoothingMode.AntiAlias;
oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
// Draw the new graphic based on the resized bitmap
oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);
PHJamesDataContext db = new PHJamesDataContext();
System.IO.MemoryStream stream = new System.IO.MemoryStream();
newBMP.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
stream.Position = 0;
byte[] data = new byte[stream.Length];
PHJProjectPhoto myPhoto =
new PHJProjectPhoto
{
ProjectPhoto = data,
OrderDate = DateTime.Now,
ProjectPhotoCaption = ProjectPhotoCaptionTextBox.Text,
ProjectId = selectedProjectId
};
db.PHJProjectPhotos.InsertOnSubmit(myPhoto);
db.SubmitChanges();
If you've got a
MemoryStream
already, just callMemoryStream.ToArray
to get the data out.Assuming, that your bitmap is bmp
You should be able to change this block to