I'm using ImageProcessor in C# and I can't come up with a way to make a generic method out of its methods as to avoid writing the same code more than once.
Say, I have two methods, crop and resize.
public Image Resize(Image image, int width, int height)
{
// Create a Image to be returned after being scaled, call it resizedImage:
Image resizedImage;
// Create a Size for the image to be scaled to, call it size:
var size = new Size(width, height);
// Create an ImageFactory to process the image, call it imageFactory:
using (var imageFactory = new ImageFactory(preserveExifData: true))
{
// Create a MemoryStream to temporarily store the processed image, call it imageStream:
using (var imageStream = new MemoryStream())
{
// Scale the image using the ImageProcessor library
// Load the image to be resized, resize it and save it to the MemoryStream:
imageFactory.Load(image)
.Resize(size)
.Save(imageStream);
// Assign the processed image to the previously declared resizedImage:
resizedImage = Image.FromStream(imageStream);
}
}
// Return the resized image:
return resizedImage;
}
public Image Crop(Image image, float left, float top, float right, float bottom, bool isModePercentage = true)
{
// Create a Image to be returned after being cropped, call it croppedImage:
Image croppedImage;
// Create a CropMode to specify what cropping method to use (Percentage or Pixels), call it cropMode
// If isModePercentage = true we use CropMode.Percentage, otherwise use CropMode.Pixels:
var cropMode = isModePercentage ? CropMode.Percentage : CropMode.Pixels;
// Create a CropLayer to specify how and how much the image should be cropped, call it cropLayer:
var cropLayer = new CropLayer(left, top, right, bottom, cropMode);
// Create an ImageFactory to process the image, call it imageFactory:
using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true))
{
// Create a MemoryStream to temporarily store the processed image, call it imageStream:
using (MemoryStream imageStream = new MemoryStream())
{
// Crop the image using the ImageProcessor library
// Load the image to be cropped, crop it and save it to the MemoryStream:
imageFactory.Load(image)
.Crop(cropLayer)
.Save(imageStream);
// Assign the processed image to the previously declared croppedImage:
croppedImage = Image.FromStream(imageStream);
}
}
// Return the cropped image:
return croppedImage;
}
How can I avoid having to instantiate imagefactory and memory stream multiple times, reducing the size of my methods and avoid to write the same code twice?