Hello I am trying to upload an image (screenshot from desktop) to SQL database
as fast as possible. I would like to optimize my current procedure in terms of speed:
bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height,
System.Drawing.Imaging.PixelFormat.Format32bppArgb);
gfxScreenshot = Graphics.FromImage(bmpScreenshot);
gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
Screen.PrimaryScreen.Bounds.Y,
0,
0,
Screen.PrimaryScreen.Bounds.Size,
CopyPixelOperation.SourceCopy);
byte[] imageBytes = convertImageToByteArray(bmpScreenshot);
MemoryStream mem = new MemoryStream(imageBytes);
using (Bitmap bmp1 = (Bitmap)Image.FromStream(mem))
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
ImageCodecInfo jgpEncoder = codecs[1];
System.Drawing.Imaging.Encoder myEncoder =
System.Drawing.Imaging.Encoder.Quality;
}
using (MemoryStream m = new MemoryStream())
{
EncoderParameters myEncoderParameters = new EncoderParameters(1);
EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 23L);
myEncoderParameters.Param[0] = myEncoderParameter;
bmp1.Save(m, jgpEncoder, myEncoderParameters);
using (Bitmap bmpLast = (Bitmap)Image.FromStream(m))
{
string query = "UPDATE ScreenCapture SET ScreenCapture=@Image,BroadcastTime=@BroadcastTime WHERE ID = 1";
SqlCommand sqlCommand = new SqlCommand(query, SQLconn);
ImageConverter converter = new ImageConverter();
byte[] beforeUpload = (byte[])converter.ConvertTo(bmpLast, typeof(byte[]));
sqlCommand.Parameters.AddWithValue("@Image", beforeUpload);
sqlCommand.Parameters.AddWithValue("@BroadcastTime", DateTime.Now);
SQLconn.Open();
sqlCommand.ExecuteNonQuery();
SQLconn.Close();
}
}
}
It now takes me about 1 second to upload and download on client side, which is not so efficient in my case. If anyone have idea how this procedure is possible to make faster I would be glad to know.
The image has around 60 KB, which is quite a lot.
Edit: Profiling - Performance and Diagnostics in Visual Studio 2013
Method I posted has following usage:
40,8% - byte[] imageBytes = convertImageToByteArray(bmpScreenshot);
10,4% - MemoryStream mem = new MemoryStream(imageBytes);
37,8% - mp1.Save(m, jgpEncoder, myEncoderParameters);
From method captureUpload
which takes 93.6% in System.Windows.Forms.ni.dll is:
69.9% System.Drawing.ni.dll
26.8% convertImageToByteArray
8.8 PresentationFramework.ni.dll
In method convertImageToByteArray
takes 26.8% on return ms.ToArray()`