2012-07-03 1 views
2

코드 스 니펫은 이미지 자르기로되어 있지만 잘라 내기 크기는 정확하지만 자르기는 왼쪽 상단에서 시작됩니다. 이 이미지는 문제를보다 명확하게 나타냅니다. herehere.이미지 자르기가 올바르게 작동하지 않습니다.

좌표는 대략 x = 68, y = 28, width = 176, height = 174입니다. 아래는 자르기 코드입니다.

/// <summary> 
/// Handles the Click event of the UploadButton control. 
/// </summary> 
/// <param name="sender">The source of the event.</param> 
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> 
/// <remarks></remarks> 
protected void UploadButton_Click(object sender, EventArgs e) 
{ 

    String path = HttpContext.Current.Request.PhysicalApplicationPath + "images\\"; 


    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) 
     { 
      ErrorLabel.Text = "File could not be uploaded." + ex.Message; 
      ErrorLabel.Visible = true; 
      FileSaved = false; 
     } 
    } 

    else 
    { 
     ErrorLabel.Text = "Cannot accept files of this type."; 
     ErrorLabel.Visible = true; 
    } 


    if (FileSaved) 
    { 
     UploadPanel.Visible = false; 
     CropPanel.Visible = true; 
     CropImage.ImageUrl = "~/Images/" + Session["WorkingImage"]; 
    } 
} 

/// <summary> 
/// Handles the Click event of the CropButton control. 
/// </summary> 
/// <param name="sender">The source of the event.</param> 
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> 
/// <remarks></remarks> 
protected void CropButton_Click(object sender, EventArgs e) 
{ 
    String path = HttpContext.Current.Request.PhysicalApplicationPath + "Images\\"; 

    string ImageName = Session["WorkingImage"].ToString(); 
    int w = Convert.ToInt32(Convert.ToDouble(W.Value)); 
    int h = Convert.ToInt32(Convert.ToDouble(H.Value)); 
    int x = Convert.ToInt32(Convert.ToDouble(X.Value)); 
    int y = Convert.ToInt32(Convert.ToDouble(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 (Image CroppedImage = Image.FromStream(ms, true)) 
     { 
      string SaveTo = path + "crop" + ImageName; 
      CroppedImage.Save(SaveTo, CroppedImage.RawFormat); 
      CropPanel.Visible = false; 
      CroppedPanel.Visible = true; 
      this.CroppedImage.ImageUrl = "~/Images/crop" + ImageName; 
     } 
    } 
} 

#endregion 

#region Methods 

/// <summary> 
/// Crops the specified image. 
/// </summary> 
/// <param name="image">The image.</param> 
/// <param name="width">The width.</param> 
/// <param name="height">The height.</param> 
/// <param name="x">The x value.</param> 
/// <param name="y">The y value.</param> 
/// <returns></returns> 
/// <remarks></remarks> 
private static byte[] Crop(string image, int width, int height, int x, int y) 
{ 
    try 
    { 
     using (Image OriginalImage = Image.FromFile(image)) 
     { 
      using (Bitmap bmp = new Bitmap(width, height)) 
      { 
       //bmp.SetResolution(OriginalImage.HorizontalResolution, OriginalImage.VerticalResolution); 

       using (Graphics Graphic = Graphics.FromImage(bmp)) 
       { 
        Graphic.SmoothingMode = SmoothingMode.AntiAlias; 
        Graphic.InterpolationMode = InterpolationMode.HighQualityBicubic; 
        Graphic.PixelOffsetMode = PixelOffsetMode.HighQuality; 
        //Graphic.DrawImage(OriginalImage, new Rectangle(0, 0, width, height), x, -y, width, height,GraphicsUnit.Pixel); 
        Graphic.DrawImage(OriginalImage, new Rectangle(0, 0, width, height), x, y, width, height, GraphicsUnit.Pixel); 
        MemoryStream ms = new MemoryStream(); 
        bmp.Save(ms, OriginalImage.RawFormat); 

        return ms.GetBuffer(); 
       } 
      } 
     } 
    } 
    catch (Exception e) 
    { 
     throw e; 
    } 
} 
+4

'자르기'를 호출하는 코드와 호출 할 때 매개 변수의 값 (너비, 높이, x, y)을 포함 할 수 있습니까? –

+1

그냥 덧글 : 예외를 잡는 데는 다시 던질 필요가 없습니다. 그리고 문제를 더욱 악화시키기 위해'throw e;'는 실제로 원래의 호출 스택을 대체 할 것입니다. –

+0

@BrianRasmussen 사실 솔직히 말해서 복사하고 붙여 넣기 만해도 걱정하지 않았지만주의 해 주셔서 감사합니다. – Lee

답변

2

자르기가 왼쪽 상단 모서리 근처에서 시작하는 것처럼 보이지 않습니다. 그것이 나에게 보이는 것은 xy 좌표가 잘못되었습니다. 원하는 이미지를 얻을 때까지 직접 xy 값을 삽입 한 다음 xy 값이 예상 한 값과 다른 이유를 직접 확인하는 것이 좋습니다.

필자가 가지고있는 (그리고 내가 작품을 알고있는) 일부 자르기 코드와 비교해 보았는데 실제 Crop 방법에는 문제가 없습니다.

+0

좋은 관찰, 나는 그것이 정말로 좌상 구석에서 정확하게 시작하지 않는다는 것을 본다. – Lee

+0

표시되는 이미지는 실제 크기가 훨씬 커질 수있는 200 * 200px로 설정됩니다. JCrop은 img 요소에서 좌표를 가져 오지만 C# 코드는 실제 이미지에서 작동합니다. 그래서 img 요소와 실제 이미지의 비율을 계산 한 다음 JCrop 값을 보정해야했습니다. 즉 일종의 스케일링 문제가있었습니다. – Lee