2012-05-31 17 views
9

Quiero tener un tamaño más pequeño en la imagen guardada. ¿Cómo puedo redimensionarlo? Puedo usar este código para redering la imagen:Cambiar el tamaño de la imagen de mapa de bits

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); 

Respuesta

3

¿Tiene su "superficie" visuales tienen capacidad de escala? Puede envolverlo en un Viewbox si no es así, luego renderice Viewbox al tamaño que desee.

Cuando llame a Medir y organizar en la superficie, debe proporcionar el tamaño que desea que sea el mapa de bits.

Para utilizar el Viewbox, cambiar el código para algo como lo siguiente:

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); 
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; 
    } 
} 
+1

Esto es perfecto sin el bloque try-catch. –

+0

La parte de Tamaño es importante, encontré varias respuestas antiguas con 2 entradas, pero ahora necesitas un tamaño. Gracias por notar eso, salvó algunos problemas. (Comentando por el bien de los futuros televidentes para saber las respuestas usando 2 ints, se debe cambiar en consecuencia) –

5

El camino más corto para cambiar el tamaño de un mapa de bits es pasarlo a un mapa de bits constructor junto con el size deseada (o width and height) :

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

@Downvoter explica por favor – Breeze

+0

Funcionó para mí. Tener un voto positivo para compensar los malos modales de alguien. – srking

+0

Funcionó perfectamente. – theMohammedA

Cuestiones relacionadas