Resize photo in C#

Today, my friend asked me to recommend a free resize photo tool, and he got lots of photos. I really don’t know. Normally I use MS Paint and select Stretch and Skew. If here are many photos, it would take ages. I then wrote a small tool for him using C#. The code is fairly simple cause .Net Framework provides huge library to use.

private void ResizePhoto()
{
	//find all jpg photos in given folder
	string[] jpgFiles = Directory.GetFiles(photoPath,"*.jpg");
	foreach(string file in jpgFiles)
	{
		//load orignial photo into memory
		Image image = Image.FromFile(file);
		//create new photo using new size from original photo
		Image newImage = new Bitmap(image,new Size(newWidth,newHeight));
		//give a new file name
		string newFileName = "newsize" + file;
		//save new photo
		newImage.Save(newFileName,System.Drawing.Imaging.ImageFormat.Jpeg);
		newImage.Dispose();
		image.Dispose();
	}
}

 

Add watermark in your photo using C#

Some of my photos need to be added watermark to prevent abusing. I just found a easy way to add watermark into your photo using C#. Here is the code to share.

private void button1_Click(object sender, System.EventArgs e)
{
	OpenFileDialog of = new OpenFileDialog();
	of.Filter = "Image Files (*.bmp;*.emf;*.exif;*.gif;*.jpg;*.png;*.tif;*.wmf)|*.bmp;*.emf;*.exif;*.gif;*.jpg;*.png;*.tif;*.wmf";

	if(of.ShowDialog(this) == DialogResult.OK)
	{
		Image image = Image.FromFile(of.FileName);
		Graphics g = Graphics.FromImage(image);

		// Create a solid brush to write the watermark text on the image
		Brush myBrush = new SolidBrush(Color.Black);
		Font myFont = this.Font;
		// Calculate the size of the text
		SizeF sz = g.MeasureString("https://www.nickdu.com", myFont);

		// drawing position (X,Y)
		float X =(image.Width - sz.Width)/2f;
		float Y = image.Height/2f;

		g.DrawString("https://www.nickdu.com",myFont,myBrush,X,Y);
		SaveFileDialog sf = new SaveFileDialog();
		sf.Filter = of.Filter;
		if(sf.ShowDialog(this) == DialogResult.OK)
		{
			image.Save(sf.FileName);
		}
		image.Dispose();
	}
}

This is the sample

watermark sample
watermark sample