Royi Namir Royi Namir -4 years ago 139
C# Question

ImageProcessor - Resize to a specified width (automatic height)

I'm using the ImageProcessor library in my App.

I'm using this code in order to resize to a given specific dimensions ( width+height) :

public static byte[] ResizeImage(byte[] inputFileBytes, int w, int h, ResizeMode resizeMode)
{
byte[] photoBytes = inputFileBytes;

ISupportedImageFormat format = new JpegFormat { Quality = 70, IsIndexed = false };
Size size = new Size(w, h);
using (MemoryStream inStream = new MemoryStream(photoBytes))
using (MemoryStream outStream = new MemoryStream())
{

using (ImageFactory imageFactory = new ImageFactory(preserveExifData: false))
{
var r = new ResizeLayer(size, resizeMode);

imageFactory.Load(inStream)
.Resize(r)
.Format(format)
.Save(outStream);
}


return outStream.ToArray();
}
}


I invoke it via (This is a crop example ):

byte[] servedImage = ResizeImage(byteArray,[...imgWidth...],
[...imgHeight...],ResizeMode.Crop);


This all works good.

But now I need to resize the image to a specific
width
— And I want the height to be proportional.

I already know that the Resize method has an overload :

public ImageFactory Resize(Size size)


But I only have the
Width
in the
size
param ( I want the height to be calculated automatically)

Question

How can I resize an Image (
byte[]
)to a specific
Width
, maintaining the aspect ration using ImageProcessor ?

Answer Source

Set the ResizeMode according to the cropping / stretching behavior you are trying to achieve. The library is designed to accommodate for differences in aspect ratio automatically depending on the chosen value for ResizeMode.

If you want to have the height auto-calculated, pass a 0 for the Height in the Size.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download