疯狂的家伙试图在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
之一,以保留原始图像的宽高比。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句