Crop image in c#

后端 未结 4 1458
梦如初夏
梦如初夏 2021-01-19 07:11

I have a image that I want to crop it when I press a button on the form. I have the following code that is run when the button is pressed, but it doesn\'t do anything to the

4条回答
  •  抹茶落季
    2021-01-19 07:13

    Your code is close to what I have been using for saving cropped images. You're missing the part where you save the cropped image. You need to write the cropped image to a byte stream then save it to disk. I modified your code, it's untested but give it a try.

    try
    {
        Image image = Image.FromFile("test.jpg");
        Bitmap bmp = new Bitmap(200, 200, PixelFormat.Format24bppRgb);
        bmp.SetResolution(80, 60);
    
        Graphics gfx = Graphics.FromImage(bmp);
        gfx.SmoothingMode = SmoothingMode.AntiAlias;
        gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;
        gfx.PixelOffsetMode = PixelOffsetMode.HighQuality;
        gfx.DrawImage(image, new Rectangle(0, 0, 200, 200), 10, 10, 200, 200, GraphicsUnit.Pixel);
    
        //Need to write the file to memory then save it
        MemorySteam ms = new MemoryStream();
        bmp.Save(ms, image.RawFormat); 
        byte[] buffer = ms.GetBuffer();
    
        var stream = new MemorySteam((buffer), 0, buffer.Length); 
        var croppedImage = SD.Image.FromStream(steam, true);
        croppedImage.Save("/your/path/image.jpg", croppedImage.RawFormat);
    
        // Dispose to free up resources
        image.Dispose();
        bmp.Dispose();
        gfx.Dispose();
        stream.Dispose();
        croppedImage.Dispose();
    
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    

提交回复
热议问题