gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:39:40 27 4
gpt4 key购买 nike

尝试在 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);
}
}

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

关于c# - 在 WPF 应用程序 c# 或 vb.net 中读取 jpg、调整大小、另存为 png,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19988520/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com