【问题标题】:Resize bitmap image调整位图图像大小
【发布时间】:2012-06-06 01:12:14
【问题描述】:

我希望保存的图像尺寸更小。 我该如何调整它的大小? 我使用此代码重新渲染图像:

Size size = new Size(surface.Width, surface.Height);
surface.Measure(size);
surface.Arrange(new Rect(size));
// Create a render bitmap and push the surface to it
RenderTargetBitmap renderBitmap =
    new RenderTargetBitmap(
        (int)size.Width,
        (int)size.Height, 96d, 96d,
        PixelFormats.Default);
renderBitmap.Render(surface);

BmpBitmapEncoder encoder = new BmpBitmapEncoder();
// push the rendered bitmap to it
encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
// save the data to the stream
encoder.Save(outStream);

【问题讨论】:

    标签: c# wpf image bitmap resize


    【解决方案1】:

    调整位图大小的最短方法是将其与所需的size(或width and height)一起传递给位图构造函数:

    bitmap = new Bitmap(bitmap, width, height);
    

    【讨论】:

    • 为我工作。投赞成票以弥补某人的不礼貌。
    • 完美运行。
    • 此解决方案的一个缺点是默认缩放针对速度进行了优化以换取质量。根据缩放的内容(和大小),这将产生锯齿和其他图形伪影。 Kashif 的解决方案可以选择缩放插值算法。
    【解决方案2】:
    public static Bitmap ResizeImage(Bitmap imgToResize, Size size)
    {
        try
        {
            Bitmap b = new Bitmap(size.Width, size.Height);
            using (Graphics g = Graphics.FromImage((Image)b))
            {
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.DrawImage(imgToResize, 0, 0, size.Width, size.Height);
            }
            return b;
        }
        catch 
        { 
            Console.WriteLine("Bitmap could not be resized");
            return imgToResize; 
        }
    }
    

    【讨论】:

    • 没有 try-catch 块是完美的。
    • 尺寸部分很重要,我找到了多个使用 2 个整数的旧答案,但您现在需要一个尺寸。感谢您注意到这一点,省去了一些麻烦。 (评论为了让未来的观众知道使用 2 个整数的答案需要相应更改)
    【解决方案3】:

    您的“表面”视觉效果是否具有缩放功能?如果没有,您可以将其包装在 Viewbox 中,然后以您想要的大小渲染 Viewbox。

    当您在表面上调用 Measure 和 Arrange 时,您应该提供您想要的位图大小。

    要使用 Viewbox,请将您的代码更改为如下所示:

    Viewbox viewbox = new Viewbox();
    Size desiredSize = new Size(surface.Width / 2, surface.Height / 2);
    
    viewbox.Child = surface;
    viewbox.Measure(desiredSize);
    viewbox.Arrange(new Rect(desiredSize));
    
    RenderTargetBitmap renderBitmap =
        new RenderTargetBitmap(
        (int)desiredSize.Width,
        (int)desiredSize.Height, 96d, 96d,
        PixelFormats.Default);
    renderBitmap.Render(viewbox);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-04
      • 1970-01-01
      • 2012-07-28
      • 2012-03-23
      • 2013-10-21
      • 1970-01-01
      相关资源
      最近更新 更多