Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize bitmap image

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);
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);
like image 844
Ionică Bizău Avatar asked May 31 '12 18:05

Ionică Bizău


People also ask

What happens when you resize a bitmap image?

When an image is resized, its pixel information is changed. For example, an image is reduced in size, any unneeded pixel information will be discarded by the photo editor (Photoshop).


2 Answers

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; 
    }
}
like image 88
Kashif Avatar answered Nov 08 '22 12:11

Kashif


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);
like image 29
Breeze Avatar answered Nov 08 '22 12:11

Breeze