2013-07-08 2 views
3

내가하고있는 일은 카드를 디자인하고 이미지를 실시간으로 표시하는 프로그램을 만드는 것입니다. 나는 그 부분을 마치고 완벽하게 잘 작동합니다. 이제 이미지를 잘라 내고 위아래에 2 개의 흰색 막대가있는 저장 방법으로 저장해야합니다. 이것은 저장을 위해 지금 사용하고있는 코드입니다.이미지 상자 컨트롤에서 이미지 자르기 및 저장

 private void SaveCardbtn_Click(object sender, EventArgs e) 
     { 
      //Open the saveFileDialog 
      if (saveWork.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
      { 
       CardImg.Image.Save(saveWork.FileName, ImageFormat.Jpeg); 
      } 
     } 

감사합니다.

+0

무엇이 문제입니까? – Ehsan

+0

질문은 어떻게 이미지를 잘라 내고 – outlaw1994

답변

3

이미이 답변을 asp.net 포럼에 게시했습니다. 이 하나의 시도하십시오 - 4 개 매개 변수를 허용합니다

다음 작물 기능 :

  1. Width

    :이 자른 이미지의 폭 될 것입니다.
  2. Height : 자른 이미지의 높이입니다.
  3. Source Image File Path : 원본 이미지 파일의 전체 경로입니다.
  4. Save Cropped Image File Path : 자른 이미지 파일의 전체 경로입니다.

    public static void CropImage(int Width, int Height, string sourceFilePath, string saveFilePath) { 
    // variable for percentage resize 
    float percentageResize = 0; 
    float percentageResizeW = 0; 
    float percentageResizeH = 0; 
    
    // variables for the dimension of source and cropped image 
    int sourceX = 0; 
    int sourceY = 0; 
    int destX = 0; 
    int destY = 0; 
    
    // Create a bitmap object file from source file 
    Bitmap sourceImage = new Bitmap(sourceFilePath); 
    
    // Set the source dimension to the variables 
    int sourceWidth = sourceImage.Width; 
    int sourceHeight = sourceImage.Height; 
    
    // Calculate the percentage resize 
    percentageResizeW = ((float)Width/(float)sourceWidth); 
    percentageResizeH = ((float)Height/(float)sourceHeight); 
    
    // Checking the resize percentage 
    if (percentageResizeH < percentageResizeW) { 
        percentageResize = percentageResizeW; 
        destY = System.Convert.ToInt16((Height - (sourceHeight * percentageResize))/2); 
    } else { 
        percentageResize = percentageResizeH; 
        destX = System.Convert.ToInt16((Width - (sourceWidth * percentageResize))/2); 
    } 
    
    // Set the new cropped percentage image 
    int destWidth = (int)Math.Round(sourceWidth * percentageResize); 
    int destHeight = (int)Math.Round(sourceHeight * percentageResize); 
    
    // Create the image object 
    using (Bitmap objBitmap = new Bitmap(Width, Height)) { 
        objBitmap.SetResolution(sourceImage.HorizontalResolution, sourceImage.VerticalResolution); 
        using (Graphics objGraphics = Graphics.FromImage(objBitmap)) { 
         // Set the graphic format for better result cropping 
         objGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; 
         objGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; 
         objGraphics.DrawImage(sourceImage, new Rectangle(destX, destY, destWidth, destHeight), new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight), GraphicsUnit.Pixel); 
    
         // Save the file path, note we use png format to support png file 
         objBitmap.Save(saveFilePath, ImageFormat.Png); 
         } 
        } 
    } 
    

전화 다음 코드를 사용하여 위의 CropImage 방법이 도움이 될 것입니다

CropImage(100, 100, "c://destinationimage.jpg", "c://newcroppedimage.jpg"); 

희망!

+0

을 저장하는 것입니다.이 덕분에 큰 감사를드립니다. 나는 imagebox와 함께 작업 할 수 있기를 바랍니다. – outlaw1994

1

이 코드를 사용하여 이미지 자르기를 수행합니다. pbOriginalImage는 이미지가있는 그림 상자입니다.

 private void pbOriginalImage_MouseDown(object sender, MouseEventArgs e) 
    { 
     try 
     { 
      // Starting point of the selection: 
      if (e.Button == MouseButtons.Left) 
      { 
       _selecting = true; 
       _selection = new Rectangle(new Point(e.X, e.Y), new Size()); 
      } 
     } 
     catch (Exception ex) 
     { 
      ApplicationExceptions.HandleAppExc(ex); 
     } 
    } 

    private void pbOriginalImage_MouseMove(object sender, MouseEventArgs e) 
    { 
     try 
     { 
      // Update the actual size of the selection: 
      if (_selecting) 
      { 
       _selection.Width = e.X - _selection.X; 
       _selection.Height = e.Y - _selection.Y; 

       // Redraw the picturebox: 
       pbOriginalImage.Refresh(); 
      } 
     } 
     catch (Exception ex) 
     { 
      ApplicationExceptions.HandleAppExc(ex); 
     } 

    } 

    private void pbOriginalImage_MouseUp(object sender, MouseEventArgs e) 
    { 
     try 
     { 
      if (pbOriginalImage.Image == null) 
       return; 

      if (e.Button == MouseButtons.Left && _selecting) 
      { 
       // check selection rectangle has non-zero Height and Width 
       if (!ValidateSelection(_selection)) 
       { 
        _selecting = false; 

        return; 
       } 

       // Check that selection rectangle does extend outside of image boundaries 
       ValidateRectangleSize(); 

       // Create cropped image: 
       Image tempImage = pbOriginalImage.Image.Clone() as Image; 
       Image img = tempImage.Crop(_selection); 



       // Fit image to the picturebox: 
       profileImage.Image = img.Fit2PictureBox(profileImage); 
       _selecting = false; 
      } 
     } 
     catch (Exception ex) 
     { 
      ApplicationExceptions.HandleAppExc(ex); 
     } 

    } 

    private void pbOriginalImage_Paint(object sender, PaintEventArgs e) 
    { 
     try 
     { 
      if (_selecting) 
      { 
       // Draw a rectangle displaying the current selection 
       Pen pen = Pens.GreenYellow; 
       e.Graphics.DrawRectangle(pen, _selection); 
      } 
     } 
     catch (Exception ex) 
     { 
      ApplicationExceptions.HandleAppExc(ex); 
      throw; 
     } 
    } 

    private void commandBrowse_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      using (OpenFileDialog dlg = new OpenFileDialog()) 
      { 
       dlg.Filter = "JPG Files (*.jpg)|*.jpg|JPEG Files (*.jpeg)|*.jpeg|bmp Files (*.bmp)|*.bmp|PNG Files (*.png)|*.png|GIF Files (*.gif)|*.gif"; 
       if (dlg.ShowDialog() == DialogResult.OK) 
       { 
        FileInfo file = new FileInfo(dlg.FileName); 

        if (file.Length == 0) 
        { 
         MessageBoxEx.Show("Invalid image. Please select valid image.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information); 
         return; 
        } 
        else if (file.Length > 2097152) 
        { 
         MessageBoxEx.Show("Image size cannot exceed 2MB.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information); 
         return; 
        } 
        textProfileImagePath.Text = dlg.FileName; 
        pbOriginalImage.Image = Image.FromFile(dlg.FileName).Fit2PictureBox(pbOriginalImage); 
        profileImage.Image = Image.FromFile(dlg.FileName).Fit2PictureBox(profileImage); 
       } 
      } 
     } 
     catch (Exception ex) 
     { 
      if (ex.Message.Contains("Out of memory")) 
      { 
       MessageBoxEx.Show("Invalid image. Please select valid image.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information); 
      } 
      else 
       ApplicationExceptions.HandleAppExc(ex); 
     } 
    } 

    // Check that selection rectangle does extend outside of image boundaries 
    private void ValidateRectangleSize() 
    { 
     Size imgSize = this.pbOriginalImage.Image.Size; 
     int selectionWidth; 
     int selectionHeight; 

     // check width 
     if (_selection.X < 0) 
     { 
      _selection.X = 0; 
     } 

     selectionWidth = _selection.Width + _selection.X; 
     if (selectionWidth > imgSize.Width) 
     { 
      _selection.Width = imgSize.Width - _selection.X - 1; 
     } 

     // check height 
     if (_selection.Y < 0) 
     { 
      _selection.Y = 0; 
     } 

     selectionHeight = _selection.Height + _selection.Y; 
     if (selectionHeight > imgSize.Height) 
     { 
      _selection.Height = imgSize.Height - _selection.Y - 1; 
     } 
    } 

    // check selection rectangle has non-zero Height and Width 
    private bool ValidateSelection(Rectangle selection) 
    { 
     // routine to validate the selection 
     if (selection.Width <= 0 || selection.Height <= 0) 
     { 
      // if you get here a good rectangle was not created 
      return false; 
     } 
     else 
     { 
      return true; 
     } 
    } 

그리고 이것은 내가 사용하는 확장 클래스입니다.

 public static class ImageExtension 
{ 
    /// <summary> 
    /// Crops an image according to a selection rectangel 
    /// </summary> 
    /// <param name="image"> 
    /// the image to be cropped 
    /// </param> 
    /// <param name="selection"> 
    /// the selection 
    /// </param> 
    /// <returns> 
    /// cropped image 
    /// </returns> 
    public static Image Crop(this Image image, Rectangle selection) 
    { 
     Bitmap bmp = image as Bitmap; 

     // Check if it is a bitmap: 
     if (bmp == null) 
      throw new ArgumentException("Not a valid image (Bitmap)"); 

     // Crop the image: 
     Bitmap cropBmp = bmp.Clone(selection, bmp.PixelFormat); 

     // Release the resources: 
     image.Dispose(); 

     return cropBmp; 
    } 
    //--------------------------------------------------------------------- 
    /// <summary> 
    /// Fits an image to the size of a picturebox 
    /// </summary> 
    /// <param name="image"> 
    /// image to be fit 
    /// </param> 
    /// <param name="picBox"> 
    /// picturebox in that the image should fit 
    /// </param> 
    /// <returns> 
    /// fitted image 
    /// </returns> 
    /// <remarks> 
    /// Although the picturebox has the SizeMode-property that offers 
    /// the same functionality an OutOfMemory-Exception is thrown 
    /// when assigning images to a picturebox several times. 
    /// 
    /// AFAIK the SizeMode is designed for assigning an image to 
    /// picturebox only once. 
    /// </remarks> 
    public static Image Fit2PictureBox(this Image image, PictureBox picBox) 
    { 
     Bitmap bmp = null; 
     Graphics g; 

     // Scale: 
     double scaleY = (double)image.Width/picBox.Width; 
     double scaleX = (double)image.Height/picBox.Height; 
     double scale = scaleY < scaleX ? scaleX : scaleY; 

     // Create new bitmap: 
     bmp = new Bitmap(
      (int)((double)image.Width/scale), 
      (int)((double)image.Height/scale)); 

     // Set resolution of the new image: 
     bmp.SetResolution(
      image.HorizontalResolution, 
      image.VerticalResolution); 

     // Create graphics: 
     g = Graphics.FromImage(bmp); 

     // Set interpolation mode: 
     g.InterpolationMode = InterpolationMode.HighQualityBicubic; 

     // Draw the new image: 
     g.DrawImage(
      image, 
      new Rectangle(   // Ziel 
       0, 0, 
       bmp.Width, bmp.Height), 
      new Rectangle(   // Quelle 
       0, 0, 
       image.Width, image.Height), 
      GraphicsUnit.Pixel); 

     // Release the resources of the graphics: 
     g.Dispose(); 

     // Release the resources of the origin image: 
     image.Dispose(); 

     return bmp; 
    } 
}