Introduction
While creating my Student Management System I have to deal with student image & there my
scenario is to store student image to a local folder situated in my project
namespace after resizing and its name (only) to database, in order to be lighten the database..
So, I do search for that almost 5 days and finally I succeeded and I m sharing it with you. Have a look...
First of all you have to import two extra libraries:
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
Write the following line globally in the form:
public Size OriginalImageSize { get; set; }
Now create some functions:
static Image ScaleByPercent(Image imgPhoto)
{
int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height;
int sourceX = 0;
int sourceY = 0;
int destX = 0;
int destY = 0;
Bitmap bmPhoto;
if (sourceWidth > sourceHeight)
{
bmPhoto = new Bitmap(300, 200, PixelFormat.Format24bppRgb);
}
else
{
bmPhoto = new Bitmap(200, 300, PixelFormat.Format24bppRgb);
}
Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
int bmPhotowidth=bmPhoto.Width;
int bmPhotoHeight = bmPhoto.Height;
if (bmPhotowidth > bmPhotoHeight)
{
grPhoto.DrawImage(imgPhoto, new Rectangle(destX, destY, 300, 200),
new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight), GraphicsUnit.Pixel);
}
else
{
grPhoto.DrawImage(imgPhoto, new Rectangle(destX, destY, 200, 300),
new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight), GraphicsUnit.Pixel);
}
grPhoto.Dispose();
return bmPhoto;
}
Now use button "browsebtn_click
" event to select image from computer:
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog opd = new OpenFileDialog();
if (opd.ShowDialog()==DialogResult.OK)
{
pictureBox2.ImageLocation = opd.FileName;
int picwidth = pictureBox2.Image.Width;
int picheight = pictureBox2.Image.Height;
string imgsize = "Original Image Width = " +
picwidth + " And Height = " + picheight;
OriginalImageSize = new Size(picwidth, picheight);
}
}
Now write a new function to store the name into database. Here I am just showing you to save image to folder and get the file name that u can store to database. I guess you know the Insert Query.. :)
private String imageUpload()
{
string imagepath = pictureBox2.ImageLocation.ToString();
string picname = imagepath.Substring(imagepath.LastIndexOf('\\'));
Image scaledImage = ScaleByPercent(pictureBox2.Image);
pictureBox2.Image = scaledImage;
string path = Application.StartupPath.Substring(0, Application.StartupPath.LastIndexOf("bin"));
Bitmap imgImage = new Bitmap(pictureBox2.Image);
if (!Directory.Exists(path + "\\images\\"))
{
Directory.CreateDirectory(path + "\\images\\");
imgImage.Save(path + "\\images\\" + picname);
}
else
{
imgImage.Save(path + "\\images\\" + picname);
}
return picname;
}
So, there you go. Hope you like this article. :)