C#使用坐标裁剪图像

时间:2017-05-11 03:36:23

标签: c# image-processing bitmap

我现在和这个争吵了一段时间,似乎无法获得任何结果。 我使用此SO QA中的方法> How to crop an image using C#?

我没有收到任何错误:/代码刚刚运行,但图片没有被裁剪。

代码:

string fileNameWitPath = "finename.png";
fileNameWitPath = context.Server.MapPath("~/content/branding/" + context.Request.QueryString["userId"] + "/logo" + "/" + fileNameWitPath)

using (FileStream fs = new FileStream(fileNameWitPath, FileMode.Open))
{
    using (BinaryWriter bw = new BinaryWriter(fs))
    {
        //get co-ords
        int x1 = Convert.ToInt32(context.Request.QueryString["x1"].Trim());
        int y1 = Convert.ToInt32(context.Request.QueryString["y1"].Trim());
        int x2 = Convert.ToInt32(context.Request.QueryString["x2"].Trim());
        int y2 = Convert.ToInt32(context.Request.QueryString["y2"].Trim());

        Bitmap b = new Bitmap(fs);
        Bitmap nb = new Bitmap((x2 - x1), (y2 - y1));
        Graphics g = Graphics.FromImage(nb);
        //g.DrawImage(b, x2, y2);
        Rectangle cropRect = new Rectangle(x1, y1, nb.Width, nb.Height);

        g.DrawImage(b, new Rectangle(x1, y1, nb.Width, nb.Height), cropRect, GraphicsUnit.Pixel);

        Byte[] data;

        using (var memoryStream = new MemoryStream())
        {
            nb.Save(memoryStream, ImageFormat.Png);
            data = memoryStream.ToArray();
        }

        bw.Write(data);
        bw.Close();
    }
}

1 个答案:

答案 0 :(得分:1)

您也可以使用Marshal.Copy复制位图之间的像素:

    static void Main()
    {
        var srcBitmap = new Bitmap(@"d:\Temp\SAE5\Resources\TestFiles\rose.jpg");
        var destBitmap = CropBitmap(srcBitmap, new Rectangle(10, 20, 50, 25));
        destBitmap.Save(@"d:\Temp\tst.png");
    }

    static Bitmap CropBitmap(Bitmap sourceBitmap, Rectangle rect)
    {
        // Add code to check and adjust rect to be inside sourceBitmap

        var sourceBitmapData = sourceBitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb);

        var destBitmap = new Bitmap(rect.Width, rect.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
        var destBitmapData = destBitmap.LockBits(new Rectangle(0, 0, rect.Width, rect.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb);

        var pixels = new int[rect.Width * rect.Height];
        System.Runtime.InteropServices.Marshal.Copy(sourceBitmapData.Scan0, pixels, 0, pixels.Length);
        System.Runtime.InteropServices.Marshal.Copy(pixels, 0, destBitmapData.Scan0, pixels.Length);

        sourceBitmap.UnlockBits(sourceBitmapData);
        destBitmap.UnlockBits(destBitmapData);

        return destBitmap;
    }