C#如何实现图片切割、切图、裁剪

这篇文章主要介绍C#如何实现图片切割、切图、裁剪,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

创新互联建站是专业的合川网站建设公司,合川接单;提供成都做网站、成都网站建设,网页设计,网站设计,建网站,PHP网站建设等专业做网站服务;采用PHP框架,可快速的进行合川网站开发网页制作和功能扩展;专业做搜索引擎喜爱的网站,专业的做网站团队,希望更多企业前来合作!

具体内容如下

前台准备两个Image控件。上面是显示原图,下面显示切割后的效果。


 
 

对应的后台代码:

public partial class MainWindow : Window
{
 public MainWindow()
 {
 InitializeComponent();

 // 设置原图
 img.Source = new BitmapImage(new Uri(@"Images/1.jpg", UriKind.Relative));

 // 切割图片
 ImageSource imageSource = img.Source;
 Bitmap bitmap = SystemUtils.ImageSourceToBitmap(imageSource);
 BitmapSource bitmapSource = SystemUtils.BitmapToBitmapImage(bitmap);
 BitmapSource newBitmapSource = SystemUtils.CutImage(bitmapSource, new Int32Rect(125, 60, 235, 285));

 // 使用切割后的图源
 img.Source = newBitmapSource;
 }

}


// 图像工具类
public static class SystemUtils
{
 /// 
 /// 切图
 /// 
 /// 图源
 /// 切割区域
 /// 
 public static BitmapSource CutImage(BitmapSource bitmapSource, Int32Rect cut)
 {
 //计算Stride
 var stride = bitmapSource.Format.BitsPerPixel * cut.Width / 8;
 //声明字节数组
 byte[] data = new byte[cut.Height * stride];
 //调用CopyPixels
 bitmapSource.CopyPixels(cut, data, stride, 0);

 return BitmapSource.Create(cut.Width, cut.Height, 0, 0, PixelFormats.Bgr32, null, data, stride);
 }

 // ImageSource --> Bitmap
 public static System.Drawing.Bitmap ImageSourceToBitmap(ImageSource imageSource)
 {
 BitmapSource m = (BitmapSource)imageSource;

 System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(m.PixelWidth, m.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

 System.Drawing.Imaging.BitmapData data = bmp.LockBits(
 new System.Drawing.Rectangle(System.Drawing.Point.Empty, bmp.Size), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

 m.CopyPixels(Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride); bmp.UnlockBits(data);

 return bmp;
 }

 // Bitmap --> BitmapImage
 public static BitmapImage BitmapToBitmapImage(Bitmap bitmap)
 {
 using (MemoryStream stream = new MemoryStream())
 {
  bitmap.Save(stream, ImageFormat.Bmp);

  stream.Position = 0;
  BitmapImage result = new BitmapImage();
  result.BeginInit();
  // According to MSDN, "The default OnDemand cache option retains access to the stream until the image is needed."
  // Force the bitmap to load right now so we can dispose the stream.
  result.CacheOption = BitmapCacheOption.OnLoad;
  result.StreamSource = stream;
  result.EndInit();
  result.Freeze();

  return result;
 }
 }
}

运行后的效果如下:

C#如何实现图片切割、切图、裁剪

补充:关于剪裁的位置和区域的填写说明,如下图。

C#如何实现图片切割、切图、裁剪

C#是什么

C#是一个简单、通用、面向对象的编程语言,它由微软Microsoft开发,继承了C和C++强大功能,并且去掉了一些它们的复杂特性,C#综合了VB简单的可视化操作和C++的高运行效率,以其强大的操作能力、优雅的语法风格、创新的语言特性和便捷的面向组件编程从而成为.NET开发的首选语言,但它不适用于编写时间急迫或性能非常高的代码,因为C#缺乏性能极高的应用程序所需要的关键功能。

以上是“C#如何实现图片切割、切图、裁剪”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注创新互联行业资讯频道!


文章标题:C#如何实现图片切割、切图、裁剪
文章转载:http://scjbc.cn/article/jhoohe.html

其他资讯