| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- using System;
- using System.Collections.Generic;
- using System.Drawing;
- using System.Drawing.Imaging;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Media.Imaging;
- namespace MvvmScaffoldFrame48.DLL.ImageAlgorithm
- {
- public static class ImageAlgorithmTools
- {
- /// <summary>
- /// 根据ROI裁剪图像
- /// </summary>
- /// <param name="sourceBitmap"></param>
- /// <param name="roi"></param>
- /// <returns></returns>
- /// <exception cref="ArgumentException"></exception>
- public static Bitmap CropBitmap(Bitmap sourceBitmap, Rectangle roi)
- {
- // 检查边界
- if (roi.X < 0 || roi.Y < 0 ||
- roi.Right > sourceBitmap.Width ||
- roi.Bottom > sourceBitmap.Height)
- {
- throw new ArgumentException("ROI区域超出源图像边界");
- }
- // 创建目标位图
- Bitmap result = new Bitmap(roi.Width, roi.Height, sourceBitmap.PixelFormat);
- // 锁定位图数据
- BitmapData sourceData = sourceBitmap.LockBits(
- new Rectangle(0, 0, sourceBitmap.Width, sourceBitmap.Height),
- ImageLockMode.ReadOnly,
- sourceBitmap.PixelFormat);
- BitmapData resultData = result.LockBits(
- new Rectangle(0, 0, result.Width, result.Height),
- ImageLockMode.WriteOnly,
- result.PixelFormat);
- try
- {
- unsafe
- {
- byte* sourcePtr = (byte*)sourceData.Scan0;
- byte* resultPtr = (byte*)resultData.Scan0;
- int pixelSize = Image.GetPixelFormatSize(sourceBitmap.PixelFormat) / 8;
- int sourceStride = sourceData.Stride;
- int resultStride = resultData.Stride;
- for (int y = 0; y < roi.Height; y++)
- {
- byte* srcRow = sourcePtr + (roi.Y + y) * sourceStride + roi.X * pixelSize;
- byte* dstRow = resultPtr + y * resultStride;
- // 复制一行像素数据
- for (int x = 0; x < roi.Width * pixelSize; x++)
- {
- dstRow[x] = srcRow[x];
- }
- }
- }
- }
- finally
- {
- sourceBitmap.UnlockBits(sourceData);
- result.UnlockBits(resultData);
- }
- return result;
- }
- /// <summary>
- /// Bitmap 转 BitmapImage 的辅助方法
- /// </summary>
- /// <param name="bitmap"></param>
- /// <returns></returns>
- public static BitmapImage ConvertToBitmapImage(Bitmap bitmap)
- {
- using (MemoryStream memory = new MemoryStream())
- {
- bitmap.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
- memory.Position = 0;
- var bitmapImage = new BitmapImage();
- bitmapImage.BeginInit();
- bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
- bitmapImage.DecodePixelWidth = 1440; // 设置目标分辨率宽度
- bitmapImage.DecodePixelHeight = 1080; // 保持宽高比
- bitmapImage.StreamSource = memory;
- bitmapImage.EndInit();
- return bitmapImage;
- }
- }
- }
- }
|