2013-11-25 72 views
0

如何裁剪在展開拉伸模式的圖片框中的圖像?如何在展開圖像的圖片框中裁剪原始圖像?

我在圖片框繪製一個矩形:

void pictureBox1_MouseUp(object sender, MouseEventArgs e) 
    { 

     //pictureBox1.Image.Clone(); 
     xUp = e.X; 
     yUp = e.Y; 
     Rectangle rec = new Rectangle(xDown, yDown, Math.Abs(xUp - xDown), Math.Abs(yUp - yDown)); 
     using (Pen pen = new Pen(Color.YellowGreen, 3)) 
     { 

      pictureBox1.CreateGraphics().DrawRectangle(pen, rec); 
     } 
     rectCropArea = rec; 
    } 

    void pictureBox1_MouseDown(object sender, MouseEventArgs e) 
    { 
     pictureBox1.Invalidate(); 

     xDown = e.X; 
     yDown = e.Y; 
    } 

和作物與所選擇的一部分:

private void btnCrop_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      pictureBox3.Refresh(); 
      //Prepare a new Bitmap on which the cropped image will be drawn 
      Bitmap sourceBitmap = new Bitmap(pictureBox1.Image, pictureBox1.Width, pictureBox1.Height); 
      Graphics g = pictureBox3.CreateGraphics(); 

      //Draw the image on the Graphics object with the new dimesions 
      g.DrawImage(sourceBitmap, new Rectangle(0, 0, pictureBox3.Width, pictureBox3.Height), rectCropArea, GraphicsUnit.Pixel); 
      sourceBitmap.Dispose(); 
     } 
     catch (Exception ex) 
     { 

     } 
    } 

但裁剪後的圖像的質量是非常低的,因爲它裁剪的拉伸圖像不是原始圖像。如何裁剪用戶在pictureBox中繪製的矩形大小的原始圖像?

+2

您必須將鼠標位置映射到圖像座標以確定需要裁剪的內容。當你使用Stretch時,它就是簡單的x = e.X * image.Width/pictureBox.Width。 –

+0

謝謝Hans Passant,它很有效。 –

+0

[使用固定大小的可拖動PictureBox的裁剪圖像] [1] [1]:https://stackoverflow.com/questions/18929261/crop-image-using-a-fixed-size-draggable -picturebox/26903361#26903361 –

回答

4

我改變pictureBox1_MouseUp代碼:

void pictureBox1_MouseUp(object sender, MouseEventArgs e) 
    { 
      xUp = e.X; 
      yUp = e.Y; 

      Rectangle rec = new Rectangle(xDown, yDown, Math.Abs(xUp - xDown), Math.Abs(yUp - yDown)); 

      using (Pen pen = new Pen(Color.YellowGreen, 3)) 
      { 

       pictureBox1.CreateGraphics().DrawRectangle(pen, rec); 
      } 

      xDown = xDown * pictureBox1.Image.Width/pictureBox1.Width; 
      yDown = yDown * pictureBox1.Image.Height/pictureBox1.Height; 

      xUp = xUp * pictureBox1.Image.Width/pictureBox1.Width; 
      yUp = yUp * pictureBox1.Image.Height/pictureBox1.Height; 

      rectCropArea = new Rectangle(xDown, yDown, Math.Abs(xUp - xDown), Math.Abs(yUp - yDown)); 
    } 

而且它的工作。感謝'Hans Passant'的回答。