/// <summary> /// 轉換圖片有效範圍 /// </summary> /// <param name="pCharsCount">int-字元數量</param> public void ConvertBmpValidRange(int pCharsCount) { // 圖片最大 X, Y,處理後變成起始 X, Y int posX1 = BmpSource.Width, posY1 = BmpSource.Height; // 圖片起始 X, Y,處理後變成最大 X, Y int posX2 = 0, posY2 = 0; // 取得有效範圍區域 for (int i = 0; i < BmpSource.Height; i++) { for (int j = 0; j < BmpSource.Width; j++) { int pixelVal = BmpSource.GetPixel(j, i).R; if (pixelVal < GrayValue) // 如像該素值低於指定灰階值則進行縮小區域 { if (posX1 > j) { posX1 = j; // 如 X2 像素位置大於圖片寬度則縮小寬度 } if (posY1 > i) { posY1 = i; // 如 Y2 像素位置大於圖片高度則縮小高度 } if (posX2 < j) { posX2 = j; // 如 X1 像素位置小於圖片寬度則縮小寬度 } if (posY2 < i) { posY2 = i; // 如 Y1 像素位置小於圖片寬度則縮小寬度 } } } } // 確保圖片可以平均切割圖片 int span = pCharsCount - (posX2 - posX1 + 1) % pCharsCount; if (span < pCharsCount) { int leftSpan = span / 2; if (posX1 > leftSpan) { posX1 = posX1 - leftSpan; } if (posX2 + span - leftSpan < BmpSource.Width) { posX2 = posX2 + span - leftSpan; } } // 產生變更後的圖片 Rectangle cloneRect = new Rectangle(posX1, posY1, posX2 - posX1 + 1, posY2 - posY1 + 1); BmpSource = BmpSource.Clone(cloneRect, BmpSource.PixelFormat); }
/// <summary> /// 切割圖片成指定目標數 /// </summary> /// <param name="pHorizontalColNumber">int-水平切割數</param> /// <param name="pVerticalRowNumber">int-垂直切割數</param> /// <returns></returns> public Bitmap[] GetSplitPicChars(int pHorizontalColNumber, int pVerticalRowNumber) { if (pHorizontalColNumber == 0 || pVerticalRowNumber == 0) { return(null); } int avgWidth = BmpSource.Width / pHorizontalColNumber; int avgHeight = BmpSource.Height / pVerticalRowNumber; // 產生存放圖片容器陣列 Bitmap[] bmpAry = new Bitmap[pHorizontalColNumber * pVerticalRowNumber]; // 重新取得數字區域 Rectangle cloneRect; for (int i = 0; i < pVerticalRowNumber; i++) { for (int j = 0; j < pHorizontalColNumber; j++) { cloneRect = new Rectangle(j * avgWidth, i * avgHeight, avgWidth, avgHeight); bmpAry[i * pHorizontalColNumber + j] = BmpSource.Clone(cloneRect, BmpSource.PixelFormat); } } return(bmpAry); }