2012-09-20 126 views
1

我有一些TIFF文件(8位調色板)。我需要將位深度更改爲32位。 我試了下面的代碼,但得到一個錯誤,參數不正確...你能幫我解決它嗎?或者也許some1能夠爲我的問題提出一些不同的解決方案。將TIFF調色板從8位更改爲32位

public static class TiffConverter 
{ 
    public static void Convert8To32Bit(string fileName) 
    { 
     BitmapSource bitmapSource; 
     using (Stream imageStreamSource = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) 
     { 
      TiffBitmapDecoder decoder = new TiffBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); 
      bitmapSource = decoder.Frames[0]; 
     } 

     using (FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate)) 
     { 
      ImageCodecInfo tiffCodec = ImageCodecInfo.GetImageEncoders().FirstOrDefault(codec => codec.FormatID.Equals(ImageFormat.Tiff.Guid)); 
      if (tiffCodec != null) 
      { 
       Image image = BitmapFromSource(bitmapSource); 
       EncoderParameters parameters = new EncoderParameters(); 
       parameters.Param[0] = new EncoderParameter(Encoder.ColorDepth, 32); 
       image.Save(stream, tiffCodec, parameters); 
      } 
     } 
    } 

    private static Bitmap BitmapFromSource(BitmapSource bitmapSource) 
    { 
     Bitmap bitmap; 
     using (MemoryStream outStream = new MemoryStream()) 
     { 
      BitmapEncoder enc = new BmpBitmapEncoder(); 
      enc.Frames.Add(BitmapFrame.Create(bitmapSource)); 
      enc.Save(outStream); 
      bitmap = new Bitmap(outStream); 
     } 
     return bitmap; 
    } 
} 

在此先感謝!

[編輯]

我注意到,在該行出現錯誤:

image.Save(stream, tiffCodec, parameters); 

ArgumentException occured: Parameter is not valid.

回答

2

如果您收到錯誤就行了:

parameters.Param[0] = new EncoderParameter(Encoder.ColorDepth, 32); 

那麼問題是th e如果你指的System.Text.EncoderSystem.Drawing.Imaging.Encoder編譯器無法知道...

您的代碼應該是這樣的,以避免任何含糊:

parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.ColorDepth, 32); 

編輯:

這是一種替代(並經過測試:))做同樣的事情的方式:

Image inputImg = Image.FromFile("input.tif"); 

var outputImg = new Bitmap(inputImg.Width, inputImg.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); 
using (var gr = Graphics.FromImage(outputImg)) 
    gr.DrawImage(inputImg, new Rectangle(0, 0, inputImg.Width, inputImg.Height)); 

outputImg.Save("output.tif", ImageFormat.Tiff); 
+0

不,因爲我創建了這樣的使用: '使用編碼器= System.Drawing.Imaging.Encoder;' – Nickon

+0

那麼你的錯誤在哪裏呢? –

+0

該死的,這是我的壞,謝謝。有一個線路參數問題:'image.Save(stream,tiffCodec,parameters);',但仍然不知道爲什麼...... – Nickon

相關問題