显示完整图像没有裁剪部分C#

问题描述:

我想比较两个图像,其中只有“打印日期”是不同的,我只想裁剪'日期'区域。但我想,以显示完整的图像,而不作物的种植面积,(不仅是农作物种植面积)我用裁剪显示完整图像没有裁剪部分C#

static void Main(string[] args) 
    { 
     Bitmap bmp = new Bitmap(@"C:\Users\Public\Pictures\Sample Pictures\1546.jpg"); 
     Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); 
     BitmapData rawOriginal = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); 

     int origByteCount = rawOriginal.Stride * rawOriginal.Height; 
     byte[] origBytes = new Byte[origByteCount]; 
     System.Runtime.InteropServices.Marshal.Copy(rawOriginal.Scan0, origBytes, 0, origByteCount); 

     //I want to crop a 100x100 section starting at 15, 15. 
     int startX = 15; 
     int startY = 15; 
     int width = 100; 
     int height = 100; 
     int BPP = 4;  //4 Bpp = 32 bits, 3 = 24, etc. 

     byte[] croppedBytes = new Byte[width * height * BPP]; 

     //Iterate the selected area of the original image, and the full area of the new image 
     for (int i = 0; i < height; i++) 
     { 
      for (int j = 0; j < width * BPP; j += BPP) 
      { 
       int origIndex = (startX * rawOriginal.Stride) + (i * rawOriginal.Stride) + (startY * BPP) + (j); 
       int croppedIndex = (i * width * BPP) + (j); 

       //copy data: once for each channel 
       for (int k = 0; k < BPP; k++) 
       { 
        croppedBytes[croppedIndex + k] = origBytes[origIndex + k]; 
       } 
      } 
     } 

     //copy new data into a bitmap 
     Bitmap croppedBitmap = new Bitmap(width, height); 
     BitmapData croppedData = croppedBitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); 
     System.Runtime.InteropServices.Marshal.Copy(croppedBytes, 0, croppedData.Scan0, croppedBytes.Length); 

     bmp.UnlockBits(rawOriginal); 
     croppedBitmap.UnlockBits(croppedData); 

     croppedBitmap.Save(@"C:\Users\Public\Pictures\Sample Pictures\AFTERCROP_CROP.jpg"); 
     bmp.Save(@"C:\Users\Public\Pictures\Sample Pictures\AFTERCROP-ORIG.jpg"); 
    } 
+0

'Graphics.DrawImage'有什么问题?至于你的问题,这没有任何意义。显示什么?哪里?或者你的意思是你想让一部分图片变黑,而不是剪下它? 'Graphics.FillRectangle'应该可以做到。 – Luaan

+0

是的,我想让剪裁部分变黑。 –

+0

这不是'cropping'这个词的意思,意思是 –

你的代码是有点过于复杂

代码,您似乎无所适从种植 - 裁剪意味着拍摄原始照片的一部分。你似乎想要代替什么是黑掉原始图像的某些部分:

Blackout versus cropping

做到这一点最简单的方法是通过在原有图像绘制简单的填充矩形:

var bmp = Bitmap.FromFile(@"C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg"); 

using (var gr = Graphics.FromImage(bmp)) 
{ 
    gr.FillRectangle(Brushes.Black, 50, 50, 200, 200); 
} 

如果您还想保留原始位图,则可以将其复制。

+0

谢谢,我昨天在我的代码中做过同样的事情,我需要多次停电。 –