Avalonia 將 DrawingImage 保存到本地文件的方法
核心需要借助 Avalonia.Media.Imaging.RenderTargetBitmap 類型,從 RenderTargetBitmap 創(chuàng)建 DrawingContext 對象,然后調(diào)用 DrawingContext 的 DrawImage 方法將 DrawingImage 繪制進入到 RenderTargetBitmap 里面,最后再調(diào)用 RenderTargetBitmap 的 Save 方法保存到本地文件
核心代碼如下,假定已經(jīng)拿到了 Avalonia.Media.DrawingImage drawingImage 對象
var imageSize = drawingImage.Size;
using var renderTargetBitmap = new RenderTargetBitmap(new PixelSize((int) imageSize.Width, (int) imageSize.Height));
using (DrawingContext drawingContext = renderTargetBitmap.CreateDrawingContext())
{
drawingContext.DrawImage(drawingImage, new Rect(new Point(), imageSize));
}
renderTargetBitmap.Save("1.png");
通過如上代碼即可將 DrawingImage 存放到本地 1.png 文件
以上方法比調(diào)用 RenderTargetBitmap 的 Render 渲染臨時創(chuàng)建的 Image 控件更好,因為以上方式開銷更小且不受樣式等的影響
// 不推薦的方法
Image image = new Image
{
Source = drawingImage,
Width = imageSize.Width,
Height = imageSize.Height
};
//image.UpdateLayout(); 調(diào)用 UpdateLayout 方法是無效的,因為 Image 沒有加入視覺樹
image.Measure(new Size(imageSize.Width, imageSize.Height));
image.Arrange(new Rect(new Point(), imageSize));
renderTargetBitmap.Render(image);
本文代碼放在 github 和 gitee 上,可以使用如下命令行拉取代碼。我整個代碼倉庫比較龐大,使用以下命令行可以進行部分拉取,拉取速度比較快
先創(chuàng)建一個空文件夾,接著使用命令行 cd 命令進入此空文件夾,在命令行里面輸入以下代碼,即可獲取到本文的代碼
git init
git remote add origin https://gitee.com/lindexi/lindexi_gd.git
git pull origin 25d5e60822d0e6b8036856b9e6e2c1329b1e5f54
以上使用的是國內(nèi)的 gitee 的源,如果 gitee 不能訪問,請?zhí)鎿Q為 github 的源。請在命令行繼續(xù)輸入以下代碼,將 gitee 源換成 github 源進行拉取代碼。如果依然拉取不到代碼,可以發(fā)郵件向我要代碼
git remote remove origin
git remote add origin https://github.com/lindexi/lindexi_gd.git
git pull origin 25d5e60822d0e6b8036856b9e6e2c1329b1e5f54
獲取代碼之后,進入 AvaloniaIDemo/RerneyawyayWilalawha 文件夾,即可獲取到源代碼
更多技術(shù)博客,請參閱 博客導航
博客園博客只做備份,博客發(fā)布就不再更新,如果想看最新博客,請訪問 https://blog.lindexi.com/
如圖片看不見,請在瀏覽器開啟不安全http內(nèi)容兼容

本作品采用知識共享署名-非商業(yè)性使用-相同方式共享 4.0 國際許可協(xié)議進行許可。歡迎轉(zhuǎn)載、使用、重新發(fā)布,但務(wù)必保留文章署名[林德熙](http://www.rzrgm.cn/lindexi)(包含鏈接:http://www.rzrgm.cn/lindexi ),不得用于商業(yè)目的,基于本文修改后的作品務(wù)必以相同的許可發(fā)布。如有任何疑問,請與我[聯(lián)系](mailto:lindexi_gd@163.com)。

浙公網(wǎng)安備 33010602011771號