C# 图片分割

发布时间 2023-08-28 15:08:41作者: SpringCore
        public Bitmap[] GetImage(int imageNum, string imagePath = "d:\\coreqi.png")
        {
            Image image = Bitmap.FromFile(imagePath);
            int rowNum = 1; //行数
            int colNum = imageNum; //列数
            int bitmapNum = rowNum * colNum; //最终多少张
            int perWidth = image.Width / colNum; //每个图片宽度
            int perHeight = image.Height / rowNum; //每个图片高度
            int srcImageX = 0;
            int srcImageY = 0;
            Bitmap[] imgs = new Bitmap[bitmapNum];
            for (int rowIdx = 0; rowIdx < rowNum; rowIdx++)
            {
                for (int colIdx = 0; colIdx < colNum; colIdx++)
                {
                    int curIdx = rowIdx * colNum + colIdx;
                    imgs[curIdx] = new Bitmap(perWidth, perHeight);
                    Graphics newBmpGraphics = Graphics.FromImage(imgs[curIdx]);
                    Rectangle destImageRect = new Rectangle(0, 0, perWidth, perHeight); //目标图片
                    Rectangle srcImageRect = new Rectangle(srcImageX, srcImageY, perWidth, perHeight); //原始图片
                    newBmpGraphics.DrawImage(image, destImageRect, srcImageRect, GraphicsUnit.Pixel);
                    newBmpGraphics.Dispose();
                    srcImageX += perWidth;
                }

                srcImageY += perHeight;
                srcImageX = 0;
            }

            return imgs;
        }