如何使PictureBox使用最近邻重采样?

时间:2008-08-26 23:07:31

标签: c# .net winforms gdi+ picturebox

我正在使用StretchImage,因为该框可以使用分割器调整大小。看起来默认是某种平滑的双线性滤波,导致我的图像模糊并具有莫尔条纹。

4 个答案:

答案 0 :(得分:31)

我也需要这个功能。我创建了一个继承PictureBox的类,覆盖OnPaint并添加一个属性以允许设置插值模式:

using System.Drawing.Drawing2D;
using System.Windows.Forms;

/// <summary>
/// Inherits from PictureBox; adds Interpolation Mode Setting
/// </summary>
public class PictureBoxWithInterpolationMode : PictureBox
{
    public InterpolationMode InterpolationMode { get; set; }

    protected override void OnPaint(PaintEventArgs paintEventArgs)
    {
        paintEventArgs.Graphics.InterpolationMode = InterpolationMode;
        base.OnPaint(paintEventArgs);
    }
}

答案 1 :(得分:5)

我怀疑你将不得不通过Image类和DrawImage函数手动调整大小并响应PictureBox上的resize事件。

答案 2 :(得分:3)

我做了一个MSDN搜索,结果发现有一篇关于此的文章,这篇文章不是很详细,但概述了你应该使用paint事件。

http://msdn.microsoft.com/en-us/library/k0fsyd4e.aspx

我编辑了一个常用的图像缩放示例来使用此功能,请参阅下面的

编辑自:http://www.dotnetcurry.com/ShowArticle.aspx?ID=196&AspxAutoDetectCookieSupport=1

希望这有帮助

    private void Form1_Load(object sender, EventArgs e)
    {
        // set image location
        imgOriginal = new Bitmap(Image.FromFile(@"C:\images\TestImage.bmp"));
        picBox.Image = imgOriginal;

        // set Picture Box Attributes
        picBox.SizeMode = PictureBoxSizeMode.StretchImage;

        // set Slider Attributes
        zoomSlider.Minimum = 1;
        zoomSlider.Maximum = 5;
        zoomSlider.SmallChange = 1;
        zoomSlider.LargeChange = 1;
        zoomSlider.UseWaitCursor = false;

        SetPictureBoxSize();

        // reduce flickering
        this.DoubleBuffered = true;
    }

    // picturebox size changed triggers paint event
    private void SetPictureBoxSize()
    {
        Size s = new Size(Convert.ToInt32(imgOriginal.Width * zoomSlider.Value), Convert.ToInt32(imgOriginal.Height * zoomSlider.Value));
        picBox.Size = s;
    }


    // looks for user trackbar changes
    private void trackBar1_Scroll(object sender, EventArgs e)
    {
        if (zoomSlider.Value > 0)
        {
            SetPictureBoxSize();
        }
    }

    // redraws image using nearest neighbour resampling
    private void picBox_Paint_1(object sender, PaintEventArgs e)
    {
        e.Graphics.InterpolationMode = InterpolationMode.NearestNeighbor;
        e.Graphics.DrawImage(
           imgOriginal,
            new Rectangle(0, 0, picBox.Width, picBox.Height),
            // destination rectangle 
            0,
            0,           // upper-left corner of source rectangle
            imgOriginal.Width,       // width of source rectangle
            imgOriginal.Height,      // height of source rectangle
            GraphicsUnit.Pixel);
    }

答案 3 :(得分:0)

在.net中调整图像大小时,System.Drawing.Drawing2D.InterpolationMode提供以下调整大小方法:

  • 双三次
  • 双线性
  • HighQualityBicubic
  • HighQualityBilinear
  • 最近邻
  • 默认