在C#中提取Image的一部分

时间:2013-10-08 15:27:21

标签: c#-4.0 asp.net-4.0

我制作了一个带有两个Picture-Box的C#Windows应用程序,一个作为MainPictureBox,另一个作为ThumbnailBox,我想在将鼠标移到主图像上并将其加载到ThumbnailPictureBox中时提取一部分Image。

1 个答案:

答案 0 :(得分:0)

这是一种从图像中获取缩略图的方法。

 public static Bitmap Thumb(this Image inputStream, int width, int height)
    {
        using (var bitMap = new Bitmap(inputStream))
        {
            int originalWidth = bitMap.Width;
            int originalHeight = bitMap.Height;
            int startPositionHeight = 0;
            int startPosionWidth = 0;
            int widthHeight = 0;

            if (originalWidth > originalHeight)
            {
                startPosionWidth = (originalWidth - originalHeight) / 2;
                widthHeight = originalHeight;
            }
            else if (originalHeight > originalWidth)
            {
                startPositionHeight = (originalHeight - originalWidth) / 2;
                widthHeight = originalWidth;
            }
            else if (originalWidth == originalHeight)
            {
                widthHeight = originalHeight;
            }

            var rect = new Rectangle(startPosionWidth, startPositionHeight, widthHeight, widthHeight);
            using (Bitmap cropped = bitMap.Clone(rect, bitMap.PixelFormat))
            {
                using (var newbitmap = new Bitmap(cropped, width, height))
                {
                    var stream = new MemoryStream();
                    newbitmap.Save(stream, ImageFormat.Tiff);
                    stream.Position = 0;

                    return new Bitmap(stream);
                }
            }
        }



    }