Skip to content

Instantly share code, notes, and snippets.

@Hades32
Created January 15, 2011 16:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Hades32/781044 to your computer and use it in GitHub Desktop.
Save Hades32/781044 to your computer and use it in GitHub Desktop.
How to get Nearest Neighbor image scaling working in Wilverlight or WP7
using System;
using System.Linq;
using System.Windows.Data;
using System.Windows.Media.Imaging;
namespace WPNearestNeighbor
{
public class PixelImageConverter : IValueConverter
{
/// <summary>
/// This converter creates a BitmapImage from image path as string that is scaled according
/// to the widht,height that is specified in the parameter
/// Expected usage:
/// <example>
/// <Image Source="{Binding Path=TheImage,
/// Converter={StaticResource PixelImageConverter1},
/// ConverterParameter=64\,64}"
/// Width="64"
/// Height="64"/>
/// </example>
/// </summary>
/// <param name="value"></param>
/// <param name="targetType"></param>
/// <param name="parameter"></param>
/// <param name="culture"></param>
/// <returns></returns>
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var val = (string)value;
var param = ((string)parameter).Split(',').Select(s => int.Parse(s)).ToArray();
var width = param[0];
var height = param[1];
var src_img = new BitmapImage(new Uri(val, UriKind.Relative));
src_img.CreateOptions = BitmapCreateOptions.None;
var src_bmp = new WriteableBitmap(src_img);
var res_bmp = new WriteableBitmap(width, height);
var xscale = (double)src_bmp.PixelWidth / (double)width;
var yscale = (double)src_bmp.PixelHeight / (double)height;
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
var xsrc = (int)(x * xscale);
var ysrc = (int)(y * yscale);
res_bmp.Pixels[x + y * width] = src_bmp.Pixels[xsrc + ysrc * src_bmp.PixelWidth];
}
}
return res_bmp;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment