Resize bitmap image

后端 未结 3 1764
陌清茗
陌清茗 2020-12-10 05:55

I want to have smaller size at image saved. How can I resize it? I use this code for redering the image:

Size size = new Size(surface.Width, surface.Height)         


        
相关标签:
3条回答
  • 2020-12-10 06:30
    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; 
        }
    }
    
    0 讨论(0)
  • 2020-12-10 06:36

    The shortest way to resize a Bitmap is to pass it to a Bitmap-constructor together with the desired size (or width and height):

    bitmap = new Bitmap(bitmap, width, height);
    
    0 讨论(0)
  • Does your "surface" visual have scaling capability? You can wrap it in a Viewbox if not, then render the Viewbox at the size you want.

    When you call Measure and Arrange on the surface, you should provide the size you want the bitmap to be.

    To use the Viewbox, change your code to something like the following:

    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);
    
    0 讨论(0)
提交回复
热议问题