gpt4 book ai didi

c# - 如何从 WPF 窗口创建缩略图并将其转换为 bytes[] 以便我可以保留它?

转载 作者:太空宇宙 更新时间:2023-11-03 20:30:37 24 4
gpt4 key购买 nike

我想从我的 wpf 窗口创建缩略图并将其保存到数据库中并稍后显示。有什么好的解决办法吗?

我已经开始使用 RenderTargetBitmap,但找不到任何简单的方法将其转换为字节。

RenderTargetBitmap bmp = new RenderTargetBitmap(180, 180, 96, 96, PixelFormats.Pbgra32);
bmp.Render(myWpfWindow);

使用 user32.dll 和 Graphics.CopyFromScreen() 对我和我都不好 因为它是here因为我也想从用户控件中截屏。

谢谢

最佳答案

Steven Robbins 写过 a great blog post关于捕获控件的屏幕截图,其中包含以下扩展方法:

public static class Screenshot
{
/// <summary>
/// Gets a JPG "screenshot" of the current UIElement
/// </summary>
/// <param name="source">UIElement to screenshot</param>
/// <param name="scale">Scale to render the screenshot</param>
/// <param name="quality">JPG Quality</param>
/// <returns>Byte array of JPG data</returns>
public static byte[] GetJpgImage(this UIElement source, double scale, int quality)
{
double actualHeight = source.RenderSize.Height;
double actualWidth = source.RenderSize.Width;

double renderHeight = actualHeight * scale;
double renderWidth = actualWidth * scale;

RenderTargetBitmap renderTarget = new RenderTargetBitmap((int) renderWidth, (int) renderHeight, 96, 96, PixelFormats.Pbgra32);
VisualBrush sourceBrush = new VisualBrush(source);

DrawingVisual drawingVisual = new DrawingVisual();
DrawingContext drawingContext = drawingVisual.RenderOpen();

using (drawingContext)
{
drawingContext.PushTransform(new ScaleTransform(scale, scale));
drawingContext.DrawRectangle(sourceBrush, null, new Rect(new Point(0, 0), new Point(actualWidth, actualHeight)));
}
renderTarget.Render(drawingVisual);

JpegBitmapEncoder jpgEncoder = new JpegBitmapEncoder();
jpgEncoder.QualityLevel = quality;
jpgEncoder.Frames.Add(BitmapFrame.Create(renderTarget));

Byte[] _imageArray;

using (MemoryStream outputStream = new MemoryStream())
{
jpgEncoder.Save(outputStream);
_imageArray = outputStream.ToArray();
}

return _imageArray;
}
}

此方法接受一个控件和一个比例因子并返回一个字节数组。所以这似乎非常符合您的要求。

查看 the post进一步阅读和一个非常简洁的示例项目。

关于c# - 如何从 WPF 窗口创建缩略图并将其转换为 bytes[] 以便我可以保留它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7754704/

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