ImageAlgorithmTools.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Drawing;
  4. using System.Drawing.Imaging;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Media.Imaging;
  10. namespace MvvmScaffoldFrame48.DLL.ImageAlgorithm
  11. {
  12. public static class ImageAlgorithmTools
  13. {
  14. public static Bitmap CropBitmap(Bitmap sourceBitmap, Rectangle roi)
  15. {
  16. // 检查边界
  17. if (roi.X < 0 || roi.Y < 0 ||
  18. roi.Right > sourceBitmap.Width ||
  19. roi.Bottom > sourceBitmap.Height)
  20. {
  21. throw new ArgumentException("ROI区域超出源图像边界");
  22. }
  23. // 创建目标位图
  24. Bitmap result = new Bitmap(roi.Width, roi.Height, sourceBitmap.PixelFormat);
  25. // 锁定位图数据
  26. BitmapData sourceData = sourceBitmap.LockBits(
  27. new Rectangle(0, 0, sourceBitmap.Width, sourceBitmap.Height),
  28. ImageLockMode.ReadOnly,
  29. sourceBitmap.PixelFormat);
  30. BitmapData resultData = result.LockBits(
  31. new Rectangle(0, 0, result.Width, result.Height),
  32. ImageLockMode.WriteOnly,
  33. result.PixelFormat);
  34. try
  35. {
  36. unsafe
  37. {
  38. byte* sourcePtr = (byte*)sourceData.Scan0;
  39. byte* resultPtr = (byte*)resultData.Scan0;
  40. int pixelSize = Image.GetPixelFormatSize(sourceBitmap.PixelFormat) / 8;
  41. int sourceStride = sourceData.Stride;
  42. int resultStride = resultData.Stride;
  43. for (int y = 0; y < roi.Height; y++)
  44. {
  45. byte* srcRow = sourcePtr + (roi.Y + y) * sourceStride + roi.X * pixelSize;
  46. byte* dstRow = resultPtr + y * resultStride;
  47. // 复制一行像素数据
  48. for (int x = 0; x < roi.Width * pixelSize; x++)
  49. {
  50. dstRow[x] = srcRow[x];
  51. }
  52. }
  53. }
  54. }
  55. finally
  56. {
  57. sourceBitmap.UnlockBits(sourceData);
  58. result.UnlockBits(resultData);
  59. }
  60. return result;
  61. }
  62. // Bitmap 转 BitmapImage 的辅助方法
  63. public static BitmapImage ConvertToBitmapImage(Bitmap bitmap)
  64. {
  65. using (MemoryStream memory = new MemoryStream())
  66. {
  67. bitmap.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
  68. memory.Position = 0;
  69. var bitmapImage = new BitmapImage();
  70. bitmapImage.BeginInit();
  71. bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
  72. bitmapImage.DecodePixelWidth = 1440; // 设置目标分辨率宽度
  73. bitmapImage.DecodePixelHeight = 1080; // 保持宽高比
  74. bitmapImage.StreamSource = memory;
  75. bitmapImage.EndInit();
  76. return bitmapImage;
  77. }
  78. }
  79. }
  80. }