2015-05-14 100 views
-1

我想比較兩個圖像,其中只有「打印日期」是不同的,我只想裁剪'日期'區域。但我想,以顯示完整的圖像,而不作物的種植面積,(不僅是農作物種植面積)我用裁剪顯示完整圖像沒有裁剪部分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'這個詞的意思,意思是 –

回答

1

你的代碼是有點過於複雜

代碼,您似乎無所適從種植 - 裁剪意味着拍攝原始照片的一部分。你似乎想要代替什麼是黑掉原始圖像的某些部分:

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

謝謝,我昨天在我的代碼中做過同樣的事情,我需要多次停電。 –