public static Bitmap ResizeNearestNeighbor(Bitmap source, int width, int height, Rectangle destinationRectangle)
{
int sourceWidth = source.Width;
int sourceHeight = source.Height;
int startX = destinationRectangle.X;
int startY = destinationRectangle.Y;
int endX = destinationRectangle.Width + startX;
int endY = destinationRectangle.Height + startY;
// Scaling factors
double widthFactor = sourceWidth / (double)destinationRectangle.Width;
double heightFactor = sourceHeight / (double)destinationRectangle.Height;
Bitmap destination = new Bitmap(width, height, PixelFormat.Format32bppPArgb);
destination.SetResolution(source.HorizontalResolution, source.VerticalResolution);
using (FastBitmap sourceBitmap = new FastBitmap(source))
{
using (FastBitmap destinationBitmap = new FastBitmap(destination))
{
// For each column
Parallel.For(
startY,
endY,
y =>
{
if (y >= 0 && y < height)
{
// Y coordinates of source points
int originY = (int)((y - startY) * heightFactor);
for (int x = startX; x < endX; x++)
{
if (x >= 0 && x < width)
{
// X coordinates of source points
int originX = (int)((x - startX) * widthFactor);
destinationBitmap.SetPixel(x, y, sourceBitmap.GetPixel(originX, originY));
}
}
}
});
}
}
source.Dispose();
return(destination);
}