Skip to content

Instantly share code, notes, and snippets.

@ChrisMoney
Last active November 10, 2016 22:59
Show Gist options
  • Save ChrisMoney/d1262f4599688695de18acfaba385eb4 to your computer and use it in GitHub Desktop.
Save ChrisMoney/d1262f4599688695de18acfaba385eb4 to your computer and use it in GitHub Desktop.
Upload File/Image in WPF, Win Forms
private void btnBrowse_Click_1(object sender, EventArgs e)
{
OpenFileDialog openFile = new OpenFileDialog();
openFile.Filter = "Images only. | *.jpg; *.jpeg; *.png; *.gif;";
DialogResult dialogResult = openFile.ShowDialog();
Image img = Image.FromFile(openFile.FileName);
// assign safe name for saving
string imgSafeName = openFile.SafeFileName;
// give generic banner name so only one file exists at a time
string[] nameArray = imgSafeName.Split('.');
string imgTempName = nameArray[0];
string extension = nameArray[1];
imgTempName = "BannerAd";
string pngString = imgTempName + ".png";
// get debug folder path
string appPath = Path.GetDirectoryName(Application.ExecutablePath) + @"\Ads\";
// check if file path exits
if (!Directory.Exists(appPath))
{
Directory.CreateDirectory(appPath);
}
// if file exists, delete existing banner ad
if (File.Exists(appPath + imgSafeName))
{
File.Delete(appPath + imgSafeName);
}
// save new banner ad
File.Copy(openFile.FileName, appPath + imgSafeName);
// If the file was not a png, reopen file and save it as a png
if (!extension.Equals("png"))
{
// resave as png
System.Drawing.Image bannerImg = System.Drawing.Image.FromFile(appPath + imgSafeName);
bannerImg.Save(appPath + pngString, System.Drawing.Imaging.ImageFormat.Png);
}
// resize png image for display
Image imgPng = Image.FromFile(appPath + pngString);
imgPng = Helper.ResizeImage(imgPng, 500);
picAdBanner.Image = imgPng;
btnDeleteImage.Visible = true;
btnBrowse.Visible = false;
lblImgStatus.Text = "Image uploaded successfully";
}
// Resize image
public static System.Drawing.Image ResizeImage(System.Drawing.Image image, int height)
{
System.Drawing.Image newImage;
if (image.Width > 1000)
{
newImage = new Bitmap(1000, height);
}
else
{
newImage = new Bitmap(image.Width, height);
}
using (Graphics GFX = Graphics.FromImage((Bitmap)newImage))
{
if (image.Width > 1000)
{
GFX.DrawImage(image, new Rectangle(0, 0, 1000, height));
}
else
{
GFX.DrawImage(image, new Rectangle(0, 0, image.Width, height));
}
}
return newImage;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment