问题
I have monochrome TIFF files (1 bpp) that I would like to write text to. When I load them into System.Drawing.Image, and try to instantiate a Graphics object from that image, I receive the error, "A Graphics object cannot be created from an image that has an indexed pixel format."
I can convert the images to a non-indexed format, such as JPEG, but then the resulting image size is very large.
I would like to accomplish this while keeping the image size down. How can I write text onto these images without converting them to another format?
回答1:
Using the idea in the comment left by Hans Passant, I located this article on code project: http://www.codeproject.com/Articles/15186/Bitonal-TIFF-Image-Converter-for-NET
Adapting this code, I converted the image to 32bpp, wrote the text on that image, then converted it to 1bpp.
回答2:
You can convert images in memory using System.Drawing.Bitmap.Clone. This satisfies the small file size requirement. If you need a TIF on winforms, use TiffBitmapEncoder.
Bitmap bmpTif = new Bitmap(imagePath);
Bitmap bmp = bmpTif.Clone(new Rectangle(0, 0, pageWidth, pageHeight),
PixelFormat.Format32bppRgb);
Graphics g = Graphics.FromImage(bmp);
// Do your g.DrawString's
Bitmap bmpNew = bmp.Clone(new Rectangle(0, 0, pageWidth, pageHeight),
PixelFormat.Format1bppIndexed);
bmpNew.Save(imagePath2);
回答3:
You could use an image manipulation API like ImageMagick.NET which supports TIFF images. I believe you can use the Annotate method to render text into it.
Hope this helps.
来源:https://stackoverflow.com/questions/10321128/write-text-to-image-with-indexed-pixel-format