How to crop an image using C#?

后端 未结 14 844
忘掉有多难
忘掉有多难 2020-11-22 05:16

How can I write an application that will crop images in C#?

相关标签:
14条回答
  • 2020-11-22 05:58

    Simpler than the accepted answer is this:

    public static Bitmap cropAtRect(this Bitmap b, Rectangle r)
    {
        Bitmap nb = new Bitmap(r.Width, r.Height);
        using (Graphics g = Graphics.FromImage(nb))
        {
            g.DrawImage(b, -r.X, -r.Y);
            return nb;
        }
    }
    

    and it avoids the "Out of memory" exception risk of the simplest answer.

    Note that Bitmap and Graphics are IDisposable hence the using clauses.

    EDIT: I find this is fine with PNGs saved by Bitmap.Save or Paint.exe, but fails with PNGs saved by e.g. Paint Shop Pro 6 - the content is displaced. Addition of GraphicsUnit.Pixel gives a different wrong result. Perhaps just these failing PNGs are faulty.

    0 讨论(0)
  • 2020-11-22 05:58

    Here's a simple example on cropping an image

    public Image Crop(string img, int width, int height, int x, int y)
    {
        try
        {
            Image image = Image.FromFile(img);
            Bitmap bmp = new Bitmap(width, height, 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, width, height), x, y, width, height, GraphicsUnit.Pixel);
            // Dispose to free up resources
            image.Dispose();
            bmp.Dispose();
            gfx.Dispose();
    
            return bmp;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
            return null;
        }            
    }
    
    0 讨论(0)
  • 2020-11-22 05:59

    If you're using AForge.NET:

    using(var croppedBitmap = new Crop(new Rectangle(10, 10, 10, 10)).Apply(bitmap))
    {
        // ...
    }
    
    0 讨论(0)
  • 2020-11-22 05:59

    This is another way. In my case I have:

    • 2 numeric updown controls (called LeftMargin and TopMargin)
    • 1 Picture box (pictureBox1)
    • 1 button that I called generate
    • 1 image on C:\imagenes\myImage.gif

    Inside the button I have this code:

    Image myImage = Image.FromFile(@"C:\imagenes\myImage.gif");
    Bitmap croppedBitmap = new Bitmap(myImage);
    croppedBitmap = croppedBitmap.Clone(
                new Rectangle(
                    (int)LeftMargin.Value, (int)TopMargin.Value,
                    myImage.Width - (int)LeftMargin.Value,
                    myImage.Height - (int)TopMargin.Value),
                System.Drawing.Imaging.PixelFormat.DontCare);
    pictureBox1.Image = croppedBitmap;
    

    I tried it in Visual studio 2012 using C#. I found this solution from this page

    0 讨论(0)
  • 2020-11-22 06:02

    here it is working demo on github

    https://github.com/SystematixIndore/Crop-SaveImageInCSharp

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
    
    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
      <title></title>
     <link href="css/jquery.Jcrop.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
    <script type="text/javascript" src="js/jquery.Jcrop.js"></script>
    </head>
    <body>
      <form id="form2" runat="server">
      <div>
        <asp:Panel ID="pnlUpload" runat="server">
          <asp:FileUpload ID="Upload" runat="server" />
          <br />
          <asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="Upload" />
          <asp:Label ID="lblError" runat="server" Visible="false" />
        </asp:Panel>
        <asp:Panel ID="pnlCrop" runat="server" Visible="false">
          <asp:Image ID="imgCrop" runat="server" />
          <br />
          <asp:HiddenField ID="X" runat="server" />
          <asp:HiddenField ID="Y" runat="server" />
          <asp:HiddenField ID="W" runat="server" />
          <asp:HiddenField ID="H" runat="server" />
          <asp:Button ID="btnCrop" runat="server" Text="Crop" OnClick="btnCrop_Click" />
        </asp:Panel>
        <asp:Panel ID="pnlCropped" runat="server" Visible="false">
          <asp:Image ID="imgCropped" runat="server" />
        </asp:Panel>
      </div>
      </form>
        <script type="text/javascript">
      jQuery(document).ready(function() {
        jQuery('#imgCrop').Jcrop({
          onSelect: storeCoords
        });
      });
    
      function storeCoords(c) {
        jQuery('#X').val(c.x);
        jQuery('#Y').val(c.y);
        jQuery('#W').val(c.w);
        jQuery('#H').val(c.h);
      };
    
    </script>
    </body>
    </html>
    

    C# code logic for upload and crop.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.IO;
    using SD = System.Drawing;
    using System.Drawing.Imaging;
    using System.Drawing.Drawing2D;
    
    namespace WebApplication1
    {
        public partial class WebForm1 : System.Web.UI.Page
        {
            String path = HttpContext.Current.Request.PhysicalApplicationPath + "images\\";
            protected void Page_Load(object sender, EventArgs e)
            {
    
            }
            protected void btnUpload_Click(object sender, EventArgs e)
            {
                Boolean FileOK = false;
                Boolean FileSaved = false;
    
                if (Upload.HasFile)
                {
                    Session["WorkingImage"] = Upload.FileName;
                    String FileExtension = Path.GetExtension(Session["WorkingImage"].ToString()).ToLower();
                    String[] allowedExtensions = { ".png", ".jpeg", ".jpg", ".gif" };
                    for (int i = 0; i < allowedExtensions.Length; i++)
                    {
                        if (FileExtension == allowedExtensions[i])
                        {
                            FileOK = true;
                        }
                    }
                }
    
                if (FileOK)
                {
                    try
                    {
                        Upload.PostedFile.SaveAs(path + Session["WorkingImage"]);
                        FileSaved = true;
                    }
                    catch (Exception ex)
                    {
                        lblError.Text = "File could not be uploaded." + ex.Message.ToString();
                        lblError.Visible = true;
                        FileSaved = false;
                    }
                }
                else
                {
                    lblError.Text = "Cannot accept files of this type.";
                    lblError.Visible = true;
                }
    
                if (FileSaved)
                {
                    pnlUpload.Visible = false;
                    pnlCrop.Visible = true;
                    imgCrop.ImageUrl = "images/" + Session["WorkingImage"].ToString();
                }
            }
    
            protected void btnCrop_Click(object sender, EventArgs e)
            {
                string ImageName = Session["WorkingImage"].ToString();
                int w = Convert.ToInt32(W.Value);
                int h = Convert.ToInt32(H.Value);
                int x = Convert.ToInt32(X.Value);
                int y = Convert.ToInt32(Y.Value);
    
                byte[] CropImage = Crop(path + ImageName, w, h, x, y);
                using (MemoryStream ms = new MemoryStream(CropImage, 0, CropImage.Length))
                {
                    ms.Write(CropImage, 0, CropImage.Length);
                    using (SD.Image CroppedImage = SD.Image.FromStream(ms, true))
                    {
                        string SaveTo = path + "crop" + ImageName;
                        CroppedImage.Save(SaveTo, CroppedImage.RawFormat);
                        pnlCrop.Visible = false;
                        pnlCropped.Visible = true;
                        imgCropped.ImageUrl = "images/crop" + ImageName;
                    }
                }
            }
    
            static byte[] Crop(string Img, int Width, int Height, int X, int Y)
            {
                try
                {
                    using (SD.Image OriginalImage = SD.Image.FromFile(Img))
                    {
                        using (SD.Bitmap bmp = new SD.Bitmap(Width, Height))
                        {
                            bmp.SetResolution(OriginalImage.HorizontalResolution, OriginalImage.VerticalResolution);
                            using (SD.Graphics Graphic = SD.Graphics.FromImage(bmp))
                            {
                                Graphic.SmoothingMode = SmoothingMode.AntiAlias;
                                Graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                                Graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
                                Graphic.DrawImage(OriginalImage, new SD.Rectangle(0, 0, Width, Height), X, Y, Width, Height, SD.GraphicsUnit.Pixel);
                                MemoryStream ms = new MemoryStream();
                                bmp.Save(ms, OriginalImage.RawFormat);
                                return ms.GetBuffer();
                            }
                        }
                    }
                }
                catch (Exception Ex)
                {
                    throw (Ex);
                }
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 06:03

    Only this sample working without problem:

    var crop = new Rectangle(0, y, bitmap.Width, h);
    var bmp = new Bitmap(bitmap.Width, h);
    var tempfile = Application.StartupPath+"\\"+"TEMP"+"\\"+Path.GetRandomFileName();
    
    
    using (var gr = Graphics.FromImage(bmp))
    {
        try
        {
            var dest = new Rectangle(0, 0, bitmap.Width, h);
            gr.DrawImage(image,dest , crop, GraphicsUnit.Point);
            bmp.Save(tempfile,ImageFormat.Jpeg);
            bmp.Dispose();
        }
        catch (Exception)
        {
    
    
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题