当前位置: 首页 > news >正文

wpf 裁剪图片并保存

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("图片保存成功!");}}}

 

http://www.rkmt.cn/news/82462.html

相关文章:

  • 2025年评价高的隧道炉红外加热型行业内知名厂家排行榜 - 品牌宣传支持者
  • windriver 第14章 USB高级功能
  • 敏感肌修护精华天花板对决:2025 年末 7 大热门精华深度测评与避坑攻略 - 速递信息
  • 2025北京比较好的留学中介机构 - 留学品牌推荐官
  • windriver 第13章:创建内核插件驱动程序
  • 2025年质量好的玻璃阳光房用户口碑最好的厂家榜 - 品牌宣传支持者
  • 2025年口碑好的净化间回收品牌公司排名,净化间回收公司TO - mypinpai
  • 2025年昆明智慧农贸集市推荐:盛鲜智慧集贸,5大优质市场全 - myqiye
  • 2025中央空调哪家好品牌TOP5权威推荐:集成化时代下的能 - 工业品牌热点
  • windriver 第12章:了解内核插件
  • 2025年知名的水泵弹簧厂家最新权威实力榜 - 行业平台推荐
  • 讲讲中央空调哪家品牌好?哪家品牌实力强? - 工业品牌热点
  • 2025年比较好的户外大型雕塑/石雕雕塑厂家最新权威实力榜 - 行业平台推荐
  • 2025北京留学机构综合实力排名 - 留学品牌推荐官
  • 2025北京哪家留学机构最好 - 留学品牌推荐官
  • 2025北京十大留学中介机构 - 留学品牌推荐官
  • 2025年下半年上海地区砂磨机设备供应商综合推荐与选择指南 - 2025年11月品牌推荐榜
  • 2025年下半年上海水溶肥设备厂家推荐top5指南 - 2025年11月品牌推荐榜
  • 2025年五大环氧胶厂家推荐,专业环氧胶厂商选购指南 - myqiye
  • 驼奶粉哪个品牌最好最正宗?口碑最好的前十名发布,国家认可的驼奶品牌有哪些? - 博客万
  • 2025年上海纳米砂磨机厂家实力排行前十名 - 2025年11月品牌推荐榜
  • 2025年12月上海卧式砂磨机厂家选购指南 - 2025年11月品牌推荐榜
  • 蓝牙/USB/冷链温湿度记录仪哪个牌子好?为你推荐靠谱厂家! - 品牌推荐大师
  • 蓝牙/USB/冷链温湿度记录仪哪个牌子好?为你推荐靠谱厂家! - 品牌推荐大师
  • 蓝牙/USB/冷链温湿度记录仪厂家:冷链监控神器?低温环境下精准?厂家经验丰富吗? - 品牌推荐大师
  • 蓝牙/USB/冷链温湿度记录仪厂家:冷链运输必备?精准记录?价格实惠? - 品牌推荐大师
  • 2025年最新工业设备选型参考:5 家钳工工作台/料架/模具架/工具柜等配套设备企业信息梳理 - 深度智识库
  • 蓝牙/USB/冷链温湿度记录仪厂家:低温环境下可靠?数据实时传输?厂家值得信赖吗? - 品牌推荐大师
  • mongo erstart error 启动失败问题解决
  • Html+css 之 div 的flex 布局分配示例(AI生成)