Search code examples
c#.netbitmapbase64crop

Cropping a Base64/Bitmap, doesn't crop it


Currently I'm making a function which can take a base64 image and crop it to the desired rectangle (X, Y, Width, Height). However, the below code doesn't seem to do the trick and I don't know why. It returns the image unchanged and uncropped.

Can anyone see the issue? :)

public static string CropImage(string base64, int x, int y, int width, int height)
        {
            byte[] bytes = Convert.FromBase64String(base64);
            using (var ms = new MemoryStream(bytes))
            {
                Bitmap bmp = new Bitmap(ms);
                Rectangle rect = new Rectangle(x, y, width, height);

                Bitmap croppedBitmap = new Bitmap(rect.Width, rect.Height, bmp.PixelFormat);

                using (Graphics gfx = Graphics.FromImage(croppedBitmap))
                {
                    gfx.DrawImage(bmp, 0, 0, rect, GraphicsUnit.Pixel);
                }

                using (MemoryStream ms2 = new MemoryStream())
                {
                    bmp.Save(ms2, ImageFormat.Jpeg);
                    byte[] byteImage = ms2.ToArray();
                    var croppedBase64 = Convert.ToBase64String(byteImage);
                    return croppedBase64;
                }
            }
        }

Solution

  • The cropped image is in croppedBitmap, bmp is the original image. I think you want to use croppedBitmap in the second memory stream:

    using (MemoryStream ms2 = new MemoryStream())
        {
            croppedBitmap.Save(ms2, ImageFormat.Jpeg);
            byte[] byteImage = ms2.ToArray();
            var croppedBase64 = Convert.ToBase64String(byteImage);
            return croppedBase64;
        }