4

我有一个功能,它需要一个位图,复制它的一部分并将其保存为 8bpp tiff。结果图像的文件名是唯一的并且文件不存在,程序有权写入目标文件夹。

void CropImage(Bitmap map) {
        Bitmap croped = new Bitmap(200, 50);

        using (Graphics g = Graphics.FromImage(croped)) {
            g.DrawImage(map, new Rectangle(0, 0, 200, 50), ...);
        }

        var encoderParams = new EncoderParameters(2);
        encoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.ColorDepth, 8L);
        encoderParams.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)EncoderValue.CompressionNone);

        croped.Save(filename, tiffEncoder, encoderParams);
        croped.Dispose();
    }

奇怪的是,这个函数在某些计算机(Win 7)上运行良好,并抛出 System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI exception on other computer(主要是 Win XP)。

所有计算机都安装了 .NET 3.5 SP1 运行时。

如果我使用它croped.Save(filename, ImageFormat.Tiff);croped.Save(filename, tiffEncoder, encoderParams);不是它适用于所有计算机,但我需要以 8bpp 格式保存 Tiff。

你有什么想法,问题可能出在哪里?

谢谢,卢卡斯

4

1 回答 1

1

GDI 是一个windows 操作系统的功能。我在处理 16 位 TIFF 文件时遇到了类似的问题,并求助于不同的库。请参阅使用 c# 中的 LibTIFF

MSDN 帮助建议该功能可用,但是当您尝试将位图复制到新位图或将其保存到文件或流时,Windows 会引发“一般错误”异常。实际上,相同的功能在 Windows7 上运行良好(似乎有很好的 TIFF 支持)。请参阅Windows 7 中的新 WIC 功能

我使用的另一个解决方案是制作 8 位的不安全副本。这样我就可以保存 PNG 文件(带有调色板)。我还没有为 TIFF 尝试过这个。

       // part of a function taking a proprietary TIFF tile structure as input and saving it into the desired bitmap format
      // tile.buf is a byterarray, containing 16-bit samples from TIFF.

        bmp = new Bitmap(_tile_width, _tile_height, PixelFormat.Format8bppIndexed);
        System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height);
        BitmapData bmpData =bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,bmp.PixelFormat);
        int bytes = bmpData.Stride * bmp.Height;

        dstBitsPalette = (byte *)bmpData.Scan0;

        offset=0;


        for (offset = 0; offset < _tile_size; offset += 2)
        {
             dstBitsPalette[offset >> 1] = tile.buf[offset + 1];
        }

        // setup grayscale palette
        ColorPalette palette = bmp.Palette;
        for (int i = 0; i < 256; i++)
        {
            Color c = Color.FromArgb(i, i, i);
            palette.Entries[i] = c;
        }
        bmp.Palette = palette;
        bmp.UnlockBits(bmpData);

        return bmp;

    }
于 2010-02-04T13:56:08.263 回答