尧图网站建设 尧图网络
  • 首页
  • 关于我们
  • 服务项目
  • 案例展示
  • 建站流程
  • 资讯中心
  • 联系我们
首页/资讯中心/详情

wpf 裁剪图片并保存

wpf 裁剪图片并保存
📅 发布时间:2026/6/18 20:44:41

xaml :

    <Window.Resources><Style x:Key="DragHandleThumbStyle" TargetType="Thumb"><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="Thumb"><Grid><Ellipse x:Name="InnerCircle" Fill="#FFFFFFFF" Stroke="#FF6A6A6A" StrokeThickness="0.5" Width="2" Height="2"/></Grid></ControlTemplate></Setter.Value></Setter></Style></Window.Resources><Grid><Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="*"/></Grid.RowDefinitions><!-- 工具栏 --><ToolBar Grid.Row="0"><Button x:Name="btnLoad" Content="加载图片" Click="BtnLoad_Click"/><Separator/><Button x:Name="btnZoomIn" Content="放大" Click="BtnZoomIn_Click"/><Button x:Name="btnZoomOut" Content="缩小" Click="BtnZoomOut_Click"/><Separator/><Button x:Name="btnRotateLeft" Content="左旋转" Click="BtnRotateLeft_Click"/><Button x:Name="btnRotateRight" Content="右旋转" Click="BtnRotateRight_Click"/><Separator/><Button x:Name="btnCrop" Content="裁剪" Click="BtnCrop_Click"/><Button x:Name="btnSave" Content="保存" Click="BtnSave_Click"/></ToolBar><!-- 图片显示区域 --><Grid Grid.Row="1"><ScrollViewer x:Name="scrollViewer" HorizontalScrollBarVisibility="Auto"VerticalScrollBarVisibility="Auto"><Viewbox x:Name="viewbox"><Grid x:Name="imageContainer"><Border BorderBrush="Black" BorderThickness="1"><Image x:Name="displayImage" Stretch="None"RenderTransformOrigin="0.5,0.5"><Image.RenderTransform><TransformGroup><ScaleTransform x:Name="scaleTransform"/><RotateTransform x:Name="rotateTransform"/></TransformGroup></Image.RenderTransform></Image></Border><!-- 裁剪选择框 --><Canvas x:Name="cropCanvas" Background="Transparent"Visibility="Collapsed"><Thumb x:Name="cropThumb" Width="100" Height="100"Canvas.Left="20" Canvas.Top="20"DragDelta="CropThumb_DragDelta"Cursor="SizeAll"><Thumb.Template><ControlTemplate><Border BorderBrush="Red" BorderThickness="0.3"Background="#4008F411"><Canvas><!-- 拖动控制点 --><Thumb x:Name="topLeft"  DragDelta="topLeft_DragDelta"Style="{StaticResource DragHandleThumbStyle}"Cursor="SizeNWSE"Canvas.Left="-1" Canvas.Top="-1"/><Thumb x:Name="topRight"  DragDelta="topRight_DragDelta"Style="{StaticResource DragHandleThumbStyle}"Cursor="SizeNESW"Canvas.Right="-1" Canvas.Top="-1"/><Thumb x:Name="bottomLeft"  DragDelta="bottomLeft_DragDelta"Style="{StaticResource DragHandleThumbStyle}"Cursor="SizeNESW"Canvas.Left="-1" Canvas.Bottom="-1"/><Thumb x:Name="bottomRight"  DragDelta="bottomRight_DragDelta"Style="{StaticResource DragHandleThumbStyle}"Cursor="SizeNWSE"Canvas.Right="-1" Canvas.Bottom="-1"/></Canvas></Border></ControlTemplate></Thumb.Template></Thumb></Canvas></Grid></Viewbox></ScrollViewer></Grid></Grid>

back code:

    public partial class MainWindow : Window{private BitmapImage originalImage;private double currentScale = 1.0;private double currentRotation = 0;public MainWindow(){InitializeComponent();}private void topLeft_DragDelta(object sender, DragDeltaEventArgs e){ResizeCropThumb(sender, e, "TopLeft");}private void topRight_DragDelta(object sender, DragDeltaEventArgs e){ResizeCropThumb(sender, e, "TopRight");}private void bottomLeft_DragDelta(object sender, DragDeltaEventArgs e){ResizeCropThumb(sender, e, "BottomLeft");}private void bottomRight_DragDelta(object sender, DragDeltaEventArgs e){ResizeCropThumb(sender, e, "BottomRight");}// 加载图片private void BtnLoad_Click(object sender, RoutedEventArgs e){OpenFileDialog openFileDialog = new OpenFileDialog{Filter = "图片文件|*.jpg;*.jpeg;*.png;*.bmp;*.gif|所有文件|*.*"};if (openFileDialog.ShowDialog() == true){try{originalImage = new BitmapImage(new Uri(openFileDialog.FileName));displayImage.Source = originalImage;currentScale = 1.0;currentRotation = 0;UpdateTransform();}catch (Exception ex){MessageBox.Show($"加载图片失败: {ex.Message}");}}}// 放大图片private void BtnZoomIn_Click(object sender, RoutedEventArgs e){currentScale *= 1.2;UpdateTransform();}// 缩小图片private void BtnZoomOut_Click(object sender, RoutedEventArgs e){currentScale /= 1.2;if (currentScale < 0.1) currentScale = 0.1;UpdateTransform();}// 左旋转private void BtnRotateLeft_Click(object sender, RoutedEventArgs e){currentRotation -= 90;UpdateTransform();}// 右旋转private void BtnRotateRight_Click(object sender, RoutedEventArgs e){currentRotation += 90;UpdateTransform();}// 更新变换private void UpdateTransform(){scaleTransform.ScaleX = currentScale;scaleTransform.ScaleY = currentScale;rotateTransform.Angle = currentRotation;}// 开始裁剪private void BtnCrop_Click(object sender, RoutedEventArgs e){if (displayImage.Source == null){MessageBox.Show("请先加载图片");return;}cropCanvas.Visibility = Visibility.Visible;}// 拖动裁剪框private void CropThumb_DragDelta(object sender, DragDeltaEventArgs e){double newLeft = Canvas.GetLeft(cropThumb) + e.HorizontalChange;double newTop = Canvas.GetTop(cropThumb) + e.VerticalChange;// 限制裁剪框不超出图片范围if (newLeft < 0) newLeft = 0;if (newTop < 0) newTop = 0;if (newLeft + cropThumb.Width > imageContainer.ActualWidth)newLeft = imageContainer.ActualWidth - cropThumb.Width;if (newTop + cropThumb.Height > imageContainer.ActualHeight)newTop = imageContainer.ActualHeight - cropThumb.Height;Canvas.SetLeft(cropThumb, newLeft);Canvas.SetTop(cropThumb, newTop);}// 调整裁剪框大小private void ResizeCropThumb(object sender, DragDeltaEventArgs e, string corner){double deltaHorizontal = e.HorizontalChange;double deltaVertical = e.VerticalChange;double newWidth = cropThumb.Width;double newHeight = cropThumb.Height;double newLeft = Canvas.GetLeft(cropThumb);double newTop = Canvas.GetTop(cropThumb);switch (corner){case "TopLeft":newWidth -= deltaHorizontal;newHeight -= deltaVertical;newLeft += deltaHorizontal;newTop += deltaVertical;break;case "TopRight":newWidth += deltaHorizontal;newHeight -= deltaVertical;newTop += deltaVertical;break;case "BottomLeft":newWidth -= deltaHorizontal;newHeight += deltaVertical;newLeft += deltaHorizontal;break;case "BottomRight":newWidth += deltaHorizontal;newHeight += deltaVertical;break;}// 限制最小尺寸if (newWidth < 10) newWidth = 10;if (newHeight < 10) newHeight = 10;// 限制不超出边界if (newLeft < 0){newWidth += newLeft;newLeft = 0;}if (newTop < 0){newHeight += newTop;newTop = 0;}if (newLeft + newWidth > imageContainer.ActualWidth)newWidth = imageContainer.ActualWidth - newLeft;if (newTop + newHeight > imageContainer.ActualHeight)newHeight = imageContainer.ActualHeight - newTop;cropThumb.Width = newWidth;cropThumb.Height = newHeight;Canvas.SetLeft(cropThumb, newLeft);Canvas.SetTop(cropThumb, newTop);e.Handled = true;}// 保存图片private void BtnSave_Click(object sender, RoutedEventArgs e){if (displayImage.Source == null) return;if (cropCanvas.Visibility == Visibility.Visible){CropAndSave();}else{SaveCurrentImage();}}// 裁剪并保存private void CropAndSave(){try{// 计算裁剪区域(考虑缩放和旋转)double scale = currentScale;double rotation = currentRotation;var leftreduce = displayImage.ActualWidth * (1 - scale) / 2;var topreduce = displayImage.ActualHeight * (1 - scale) / 2;// 获取裁剪框相对于图片的位置double left = (Canvas.GetLeft(cropThumb) - leftreduce) / scale;double top = (Canvas.GetTop(cropThumb) - topreduce) / scale;double width = cropThumb.Width / scale;double height = cropThumb.Height / scale;// 创建裁剪后的图片CroppedBitmap croppedBitmap = new CroppedBitmap((BitmapSource)displayImage.Source,new Int32Rect((int)left, (int)top, (int)width, (int)height));// 保存对话框SaveFileDialog saveDialog = new SaveFileDialog{Filter = "PNG 图片|*.png|JPEG 图片|*.jpg|BMP 图片|*.bmp"};if (saveDialog.ShowDialog() == true){string filename = saveDialog.FileName;string extension = System.IO.Path.GetExtension(filename).ToLower();BitmapEncoder encoder;switch (extension){case ".jpg": encoder = new JpegBitmapEncoder(); break;case ".jpeg": encoder = new JpegBitmapEncoder(); break;case ".bmp": encoder = new BmpBitmapEncoder(); break;default: encoder = new PngBitmapEncoder(); break;}encoder.Frames.Add(BitmapFrame.Create(croppedBitmap));using (FileStream stream = new FileStream(filename, FileMode.Create)){encoder.Save(stream);}MessageBox.Show("图片保存成功!");cropCanvas.Visibility = Visibility.Collapsed;}}catch (Exception ex){MessageBox.Show($"保存失败: {ex.Message}");}}// 保存当前图片private void SaveCurrentImage(){if (!(displayImage.Source is BitmapSource)) return;BitmapSource source = displayImage.Source as BitmapSource;SaveFileDialog saveDialog = new SaveFileDialog{Filter = "PNG 图片|*.png|JPEG 图片|*.jpg|BMP 图片|*.bmp"};if (saveDialog.ShowDialog() == true){string extension = System.IO.Path.GetExtension(saveDialog.FileName).ToLower();BitmapEncoder encoder;switch (extension){case ".jpg": encoder = new JpegBitmapEncoder(); break;case ".jpeg": encoder = new JpegBitmapEncoder(); break;case ".bmp": encoder = new BmpBitmapEncoder(); break;default: encoder = new PngBitmapEncoder(); break;}encoder.Frames.Add(BitmapFrame.Create(source));using (FileStream stream = new FileStream(saveDialog.FileName, FileMode.Create)){encoder.Save(stream);}MessageBox.Show("图片保存成功!");}}}

 

相关新闻

  • 2025年评价高的隧道炉红外加热型行业内知名厂家排行榜 - 品牌宣传支持者
  • windriver 第14章 USB高级功能
  • 敏感肌修护精华天花板对决:2025 年末 7 大热门精华深度测评与避坑攻略 - 速递信息

最新新闻

  • 2026防晒墨镜哪些品牌排名高?TOP5清单出炉 - 速递信息
  • 上海汽车音响改装选哪家?上海音乐人生,二十年赛事级连锁标杆门店 - 音乐人生汽车音响
  • 技术解析:从Tri-Plane到3D GAN,如何实现高效且一致的神经渲染
  • 通过Selenium实现网页截图来生成应用封面
  • 2026苏州钻石回收实测|国标4C定级,全城无套路靠谱门店变现指南 - 薛定谔的梨花猫
  • C语言宽字符处理:wmemcmp、wmemcpy、wprintf核心函数详解与实战

日新闻

  • 5分钟掌握Python进化算法:Geatpy高性能优化工具完全指南
  • Microchip 24AA044 EEPROM选型与应用全指南:从参数解析到实战编程
  • 华为的鸿蒙到底有多牛?为什么称作遥遥领先?

周新闻

  • 3步解锁iOS设备:applera1n激活锁绕过完全指南
  • 39 2026 人工智能证书终极盘点,普通人选 AI 证书可以从这些方向入手
  • Redis 暴露公网有多危险?从端口检查到补救步骤

月新闻

  • 【总结】入门篇:50句话让你记住架构核心概念
  • WeChatMsg技术方案解析:实现Mac微信数据自主管理的完整解决方案
  • WeChatMsg:革新性微信数据备份方案,打造你的专属数字记忆库

关于尧图

  • 公司简介
  • 团队介绍
  • 企业文化
  • 荣誉资质

服务项目

  • 定制开发
  • 电商建站
  • UI 设计
  • 运维服务

快速链接

  • 案例展示
  • 建站流程
  • 常见问题
  • 资讯中心

联系方式

  • 📍北京市朝阳区互联网产业园 A 座 10 层
  • 📞400-888-8888
  • ✉️contact@rkmt.cn
  • 🕐周一至周日 9:00-21:00

© 2024 北京尧图网络科技有限公司 版权所有 | 京 ICP 备 XXXXXXXX 号