2014-02-20 44 views
-1

嗨,大家我想将所有图像转换为我的目录中的灰度,但是我知道的代码只能一个接一个地完成这个任务!!但是我有很多图像,而且我希望如果有该转换所有图像目录代码为灰度或使用C#将图像转换为灰度使用C#

+1

[C#,可将图像转换为灰度](http://stackoverflow.com/questions/2265910/c-convert-image-to-grayscale) – Annabelle

+0

Th是一个问题和答案网站来帮助解决发展问题。你可以用google搜索这个问题,并找到很多答案。考虑向我们展示您尝试过的一些代码,我们很乐意为您提供帮助。 –

+0

搜索“批量转换图像”或“批量转换图像”。有许多不同的程序会为你做到这一点。 –

回答

1

假设你有一个名为path变量,它是处理图像的文件夹的路径,并假设您可以使用WPF的API,将图像转换:

DirectoryInfo dirInfo = new DirectoryInfo(path); 

foreach (FileInfo fileInfo in dirInfo.EnumerateFile()) { 
    ProcessImage(FileInfo.FullName); 
} 

void ProcessImage(string image) { 
    byte[] imageData = null; 

    try { 
     // Load the data in the file into a byte array for processing. 
     imageData = File.ReadAllBytes(image); 

    } catch (Exception) { 
     // Your error handling code here 
    } 

    // We're going to put the image into this object 
    BitmapImage src = new BitmapImage(); 

    try { 
     // Load the image into a memory stream, then into src. 
     using(MemoryStream stream = new MemoryStream(imageData)) { 
      src.BeginInit(); 
      src.CacheOption = BitmapCacheOption.OnLoad; // Causes the bitmap data to be loaded now, not at a later time. 
      src.StreamSource = stream; 
      src.EndInit(); 
     } 
    } catch (NotSupportedException) { 
     // The bitmap format is not supported. Your error handler here. 
    } 

    try { 
     // Create a FormatConvertedBitmap object & set it up. 
     FormatConvertedBitmap dst = new FormatConvertedBitmap(); 
     dst.BeginInit(); 
     dst.DestinationFormat = PixelFormats.Gray8; // Use whatever gray scale format you need here 
     dst.Source   = src; 

     // Now convert the image to 8 bits per pixel grey scale. 
     dst.EndInit(); 

     // Compute the dst Bitmap's stride (the length of one row of pixels in bytes). 
     int stride = ((dst.PixelWidth * dst.Format.BitsPerPixel + 31)/32) * 4; 

     // Allocate space for the imageBytes array. 
     imageBytes = new byte[ stride * dst.PixelHeight ]; 

     // Get the pixels out of the dst image and put them into imageBytes. 
     dst.CopyPixels(Int32Rect.Empty, imageBytes, stride, 0); 

    } catch (Exception ex) { 
     // Your error handler here. 
    } 

    // Any other code to save or do something else with the image. 
} 
+0

是的,我想要这部分代码DirectoryInfo dirInfo = new DirectoryInfo(path); foreach(FileInfo fileInfo in dirInfo.EnumerateFile()){ ProcessImage(FileInfo.FullName); }但我想使用opencv转换成灰度,所以我读所有的字节转换使用图片成灰色? – Johana

+0

@Johana恐怕我没有opencv的经验,对不起。 –

+0

我不在乎!!你的信息帮助我很多!!别担心! – Johana