2012-05-31 55 views
9

画像を保存する際のサイズを小さくしたい。 どのようにサイズを変更できますか? 私は画像をrederingため、このコードを使用します。ビットマップ画像のサイズを変更

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

答えて

3

あなたの「表面」のビジュアルは、機能を拡大縮小しているのか? Viewboxに入れない場合は、Viewboxでラップしてから、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); 
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

これはtry-catchブロックなしでは完璧です。 –

+0

サイズの部分が重要です、私は2つのintを使用して複数の古い答えを見つけましたが、今はサイズが必要です。それに気づいてくれてありがとう、何か問題を救った。 (2人のintを使って将来の視聴者が回答を知るためのコメントは –

5

ビットマップのサイズを変更する最短の方法は、希望size(またはwidth and height)と一緒にビットマップ・コンストラクタに渡すことです:

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

@Downvoter please explain – Breeze

+0

私のために働いた。誰かの悪いマナーを補うためにアップコートを持ってください。 – srking

+0

完璧に作業しました。 – theMohammedA

関連する問題