阅读jpg,调整大小,在WPF应用程序c#或vb.net中另存为png

时间:2013-11-14 21:14:22

标签: c# wpf bitmap imagesource

试图在WPF(使用所有新的图像处理工具)中尝试这样做,但似乎找不到可行的解决方案。到目前为止,所有解决方案都是在屏幕上绘制或进行多次保存,但我需要在内存中完全执行此操作。

基本上,我想将一个大的jpeg加载到内存中,将其调整得更小(在内存中),保存为一个小的PNG文件。 我可以将jpeg文件加载到BitMap对象中,很好。在那之后,我很难过。

我发现这个函数看起来像是技巧但它需要一个ImageSource(遗憾的是,我找不到一种方法将我的内存中BitMap对象转换为不会产生NULL异常的ImageSource。)< / p>

private static BitmapFrame CreateResizedImage(ImageSource source, int width, int height, int margin)
{
    dynamic rect = new Rect(margin, margin, width - margin * 2, height - margin * 2);

    dynamic @group = new DrawingGroup();
    RenderOptions.SetBitmapScalingMode(@group, BitmapScalingMode.HighQuality);
    @group.Children.Add(new ImageDrawing(source, rect));

    dynamic drawingVisual = new DrawingVisual();
    using (drawingContext == drawingVisual.RenderOpen()) 
    {
        drawingContext.DrawDrawing(@group);
    }

    // Resized dimensions
    // Default DPI values
    dynamic resizedImage = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Default);
    // Default pixel format
    resizedImage.Render(drawingVisual);

    return BitmapFrame.Create(resizedImage);
}

1 个答案:

答案 0 :(得分:4)

使用WPF就像这样简单:

private void ResizeImage(string inputPath, string outputPath, int width, int height)
{
    var bitmap = new BitmapImage();

    using (var stream = new FileStream(inputPath, FileMode.Open))
    {
        bitmap.BeginInit();
        bitmap.DecodePixelWidth = width;
        bitmap.DecodePixelHeight = height;
        bitmap.CacheOption = BitmapCacheOption.OnLoad;
        bitmap.StreamSource = stream;
        bitmap.EndInit();
    }

    var encoder = new PngBitmapEncoder();
    encoder.Frames.Add(BitmapFrame.Create(bitmap));

    using (var stream = new FileStream(outputPath, FileMode.Create))
    {
        encoder.Save(stream);
    }
}

您可以考虑仅设置DecodePixelWidthDecodePixelHeight中的一个,以保留原始图像的宽高比。

相关问题