Bitmap.Save保留旧的PixelFormat

时间:2014-12-26 17:04:11

标签: c# c#-4.0 image-processing jpeg tiff

我正在使用以下代码将一堆TIFF图像转换为JPEG。我遇到的问题是图像尺寸在黑白图像上呈指数级增长,上面有很多黑色斑点。我发现进入的图像(TIFF)是PixelFormat Format1bppIndexed,但它总是将它们保存为JPEG格式24bppRgb。有没有办法始终保持原始图像的PixelFormat,所以这个问题不会发生?原始图像的PixelFormat并不总是相同,因为图像是彩色,b& W,灰度。

 public static string[] ConvertTiffToJpeg(string fileName)
        {
            using (Image imageFile = Image.FromFile(fileName))
            {
                var test = imageFile.PixelFormat;

                FrameDimension frameDimensions = new FrameDimension(
                    imageFile.FrameDimensionsList[0]);

                // Gets the number of pages from the tiff image (if multipage) 
                int frameNum = imageFile.GetFrameCount(frameDimensions);
                string[] jpegPaths = new string[frameNum];

                for (int frame = 0; frame < frameNum; frame++)
                {
                    // Selects one frame at a time and save as jpeg. 
                    imageFile.SelectActiveFrame(frameDimensions, frame);
                    using (Bitmap bmp = new Bitmap(imageFile))
                    {
                        jpegPaths[frame] = String.Format("{0}\\{1}{2}.jpg",
                            Path.GetDirectoryName(fileName),
                            Path.GetFileNameWithoutExtension(fileName),
                            frame);
                        bmp.Save(jpegPaths[frame], ImageFormat.Jpeg);
                    }
                }

                return jpegPaths;
            }
    }

1 个答案:

答案 0 :(得分:1)

.jpg文件为24位彩色或8位灰度。您可以将8位灰度用于1 bpp黑白tiff图像并节省一些空间,但不能使用索引颜色或每像素1位与.jpg文件。

根据图像目标应用程序,您可以将1 bpp tiff图像保存为.png或.gif图像而不是.jpg。如果使用索引颜色或1 bpp保存,那应该与tiff文件一样小。