【问题标题】:Cropping a Base64/Bitmap, doesn't crop it裁剪 Base64/位图,不裁剪
【发布时间】:2019-05-10 07:42:11
【问题描述】:

目前我正在制作一个可以获取 base64 图像并将其裁剪为所需矩形(X、Y、宽度、高度)的函数。但是,下面的代码似乎没有奏效,我不知道为什么。它返回未更改且未裁剪的图像。

谁能看到这个问题? :)

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;
                }
            }
        }

【问题讨论】:

    标签: c# .net bitmap base64 crop


    【解决方案1】:

    裁剪后的图像在croppedBitmapbmp 是原始图像。我想你想在第二个内存流中使用croppedBitmap

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

    【讨论】:

    • 成功了!这完全有道理,我这边的错误! :) 谢谢!
    猜你喜欢
    • 2016-08-27
    • 2022-01-23
    • 2015-12-11
    • 1970-01-01
    • 1970-01-01
    • 2013-03-25
    • 1970-01-01
    • 2015-05-05
    • 1970-01-01
    相关资源
    最近更新 更多