Skip to main content
 首页 » 编程设计

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

2024年02月13日18grandyang

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

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

我发现这个函数看起来可以解决问题,但它需要一个 ImageSource(不幸的是,我找不到将内存中的 BitMap 对象转换为不产生 NULL 异常的 ImageSource 的方法。)

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

请您参考如下方法:

使用 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); 
    } 
} 

您可以考虑只设置 DecodePixelWidth 和 DecodePixelHeight 之一,以保持原始图像的纵横比。