[C#] Image Codecs - Transforming An Image

AceInfinity

Emeritus, Contributor
Joined
Feb 21, 2012
Posts
1,728
Location
Canada
I've been exploring more documentation today, and there hasn't been much on Imaging yet here, so I thought I'd post an example on how to utilize an ImageCodec and Encoders to transform an image and save it back to the filesystem. In my example, I save/create a backup just in case, for convenience.

Code:
private unsafe void MainMethod()
{
	FlipImgHorizontal(@"Z:\IMG\girl.jpg", "image/jpeg");
}

private void FlipImgHorizontal(string fileName, string mimeType)
{
	ImageCodecInfo imgCodec;
	ImgEncoder enc;

	string bakupFile = fileName + ".bak";
	File.Copy(fileName, bakupFile, true);

	imgCodec = ImageCodecInfo.GetImageEncoders().FirstOrDefault(e => e.MimeType == mimeType);
	if (imgCodec == null)
		throw new ArgumentException("Invalid MimeType specified.");

	enc = ImgEncoder.Transformation;

	using (Bitmap bmp = new Bitmap(bakupFile))
	{
		using (EncoderParameters encParams = new EncoderParameters(1))
		{
			using (EncoderParameter encParam = new EncoderParameter(enc, (long)EncoderValue.TransformFlipHorizontal))
			{
				encParams.Param[0] = encParam;
				bmp.Save(fileName, imgCodec, encParams);
			}
		}
	}
}

Note: ImgEncoder is my own definition...
Code:
using BitmapEncoder = System.Drawing.Imaging.Encoder;

Some valid MimeTypes are listed below:
Code:
image/bmp
image/jpeg
image/gif
image/tiff
image/png

:wave:
 

Has Sysnative Forums helped you? Please consider donating to help us support the site!

Back
Top