2012-09-20 129 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

相关问题