无法将TIFF文件读入Bitmap对象 [英] Can't read a TIFF file into a Bitmap object
问题描述
大家好;
请查看
TiffIssue.zip 。这有一个测试程序来显示问题和有问题的tiff文件。 Paint可以打开tiff文件,但是Bitmap类会尝试实例化它。
Please look at TiffIssue.zip. This has a test program to show the issue and the problematic tiff file. Paint can open the tiff file but the Bitmap class throws an exception trying to instantiate it.
知道为什么吗?
谢谢 - 戴夫
过去6个月我们做了什么 -
使世界上最酷的报道和docgen系统更加惊人
What we did for the last 6 months - Made the world's coolest reporting & docgen system even more amazing
推荐答案
嗨DavidThi808,
Hi DavidThi808,
感谢您发布此处。
对于您的问题,如果您想阅读带有位图的TIFF,请尝试以下代码。
For your question, if you want to read TIFF with Bitmap, please try the code below.
class TIFF_to_Bitmap
{
static void Main(string[] args)
{
string filename = "1.jpg";
Bitmap oBmp = TiffToBitmap("image1.tif");
oBmp.Save(filename);
Bitmap bmp = new Bitmap(new FileStream(filename, FileMode.Open, FileAccess.Read));
Console.Out.WriteLine("open successful");
Console.ReadKey();
}
private static Bitmap TiffToBitmap(string asTiffFile)
{
Bitmap bmp = null;
try
{
bmp = (Bitmap)Bitmap.FromFile(asTiffFile);
return bmp;
}
catch
{
}
Tiff tif = Tiff.Open(asTiffFile, "r");
if (tif == null)
{
return null;
}
// Find the width and height of the image
FieldValue[] value = tif.GetField(TiffTag.IMAGEWIDTH);
int width = value[0].ToInt();
value = tif.GetField(TiffTag.IMAGELENGTH);
int height = value[0].ToInt();
// Read the image into the memory buffer
int[] raster = new int[height * width];
if (!tif.ReadRGBAImage(width, height, raster))
{
tif.Close();
tif.Dispose();
return null;
}
tif.Close();
tif.Dispose();
// bitmap
bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb);
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
BitmapData bmpdata = bmp.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
byte[] bits = new byte[bmpdata.Stride * bmpdata.Height];
for (int y = 0; y < bmp.Height; y++)
{
int rasterOffset = y * bmp.Width;
int bitsOffset = (bmp.Height - y - 1) * bmpdata.Stride;
for (int x = 0; x < bmp.Width; x++)
{
int rgba = raster[rasterOffset++];
bits[bitsOffset++] = (byte)((rgba >> 16) & 0xff);
bits[bitsOffset++] = (byte)((rgba >> 8) & 0xff);
bits[bitsOffset++] = (byte)(rgba & 0xff);
}
}
Marshal.Copy(bits, 0, bmpdata.Scan0, bits.Length);
bmp.UnlockBits(bmpdata);
return bmp;
}
我将.tif文件转换为.jpg文件然后读取它。我显示.jpg文件。
I convert the .tif file to .jpg file and then read it. I show the .jpg file.
最好的问候,
Wendy
这篇关于无法将TIFF文件读入Bitmap对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!