如何裁剪图像并调整其大小?

时间:2014-11-28 11:39:28

标签: c# wpf

我试图裁剪并调整Steve的头部,这是Minecraft的默认皮肤! : - )

但是我遇到了一些问题,我得到了裁剪,但调整大小不起作用,图像模​​糊不清: - (

我的XAML:

<Image Height="60" Width="60" Name="ProfileImage" Stretch="UniformToFill" />

我的代码背后:

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        System.Drawing.Rectangle cropRect = new System.Drawing.Rectangle(8,8,8,8);
        Bitmap source = System.Drawing.Image.FromFile("steve.png") as Bitmap;
        Bitmap target = new Bitmap(60, 60);

        using(Graphics g = Graphics.FromImage(target))
        {
            g.DrawImage(source, 
                new System.Drawing.Rectangle(0, 0, target.Width, target.Height), 
                cropRect, 
                GraphicsUnit.Pixel);
            g.Dispose();

           ProfileImage.Source = CreateBitmapSourceFromBitmap(target);
        }
    }

    public static BitmapSource CreateBitmapSourceFromBitmap(Bitmap bitmap)
    {
        if (bitmap == null)
            throw new ArgumentNullException("bitmap");

        return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
            bitmap.GetHbitmap(),
            IntPtr.Zero,
            Int32Rect.Empty,
            BitmapSizeOptions.FromEmptyOptions());
    }

有没有人有线索?皮肤看起来像这样,我想要的头部是(8,8,8(宽),8(高)):

enter image description here

2 个答案:

答案 0 :(得分:2)

如果您希望在调整大小时保留方形像素形状,则只需更改用于绘制的Graphics对象的插值模式:

g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;

g.DrawImage(source,
            new System.Drawing.Rectangle(0, 0, target.Width, target.Height),
            cropRect,
            GraphicsUnit.Pixel);

下面显示左侧的NearestNeighbor插值和右侧的Default(双线性)插值。

enter image description here

答案 1 :(得分:2)

通过在Image控件上将RenderOptions.BitmapScalingMode设置为NearestNeighbor,您可以在没有任何WinForms(System.Drawing)的情况下执行此操作

<Image Height="60" Width="60" Name="ProfileImage" Stretch="UniformToFill"
       RenderOptions.BitmapScalingMode="NearestNeighbor"/>

并使用CroppedBitmap作为图片的Source

var steve = new BitmapImage(new Uri("steve.png", UriKind.Relative));
ProfileImage.Source = new CroppedBitmap(steve, new Int32Rect(8, 8, 8, 8));

您甚至可以在XAML中完全执行此操作:

<Image Height="60" Width="60" RenderOptions.BitmapScalingMode="NearestNeighbor">
    <Image.Source>
        <CroppedBitmap Source="steve.png" SourceRect="8,8,8,8"/>
    </Image.Source>
</Image>