c# - LibTiff.Net 将 Tiff 对象转换为字节数组并返回

标签 c# arrays type-conversion tiff libtiff.net

您好,我找不到将多页 tiff 图像转换为字节数组的示例。

为了将字节数组转换为 Tiff,我使用这种方法

    public static Tiff CreateTiffFromBytes(byte[] bytes)
    {
        using (var ms = new MemoryStream(bytes))
        {
            Tiff tiff = Tiff.ClientOpen("in-memory", "r", ms, new TiffStream());
            return tiff;
        }
    }

已编辑:

此方法将多页的 TIFF 图像转换为字节数组。我认为这种方法将是问题的根源。

    //imageIn is tif image with 12 pages
    public static byte[] ImageToByteArray(System.Drawing.Image imageIn)
    {       
        using (var ms = new MemoryStream())
        {
            imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Tiff);
            return ms.ToArray();
        }
    }

   public static List<System.Drawing.Image> GetAllPages(System.Drawing.Image multiTiff)
    {
        var images = new List<System.Drawing.Image>();
        var bitmap = (Bitmap)multiTiff;
        int count = bitmap.GetFrameCount(FrameDimension.Page);

        for (int idx = 0; idx < count; idx++)
        {
            bitmap.SelectActiveFrame(FrameDimension.Page, idx);
            using (var byteStream = new MemoryStream())
            {
                bitmap.Save(byteStream, ImageFormat.Tiff);

                images.Add(System.Drawing.Image.FromStream(byteStream));
            }
        }
        return images;
    }

转换为字节数组后,我丢失了页面。 来自字节数组的图像只有一页。

  Image src = Image.FromFile(source);
    //imagesInSource.Count (pages) is 12
    List<Image> imagesInSource = GetAllPages(src);

    byte[] imageData = ImageToByteArray(src);

    Image  des = ImageConvert.ByteArrayToImage(imageData);
    //imagesInSource.Count (pages) is 1
    List<Image> imagesInDes = GetAllPages(des);

最佳答案

我不确定为什么不能将 TIFF 文件发送到服务?毕竟,文件只是字节。

并且您在第一个片段中的代码不正确,因为您处理了传递给 Tiff 对象的内存流。你不应该那样做。 Tiff 对象将处理流本身。

编辑:

在第三个片段中,您为 System.Drawing.Image 的每个页面创建图像,但您只将第一个生成的图像转换为字节数组。你应该使用类似的东西

List<byte[]> imagesBytes = new List<byte[]>();
foreach (Image img in imagesInSource)
{
    byte[] imageData = ImageToByteArray(src);
    imageBytes.Add(imageData);
}

然后您应该将 imagesBytes 发送到您的服务器并从中创建多个 TIFF 图像。

无论如何,您似乎应该多考虑一下您真正想要做什么。因为目前我还不清楚所有这些转换的目的。

关于c# - LibTiff.Net 将 Tiff 对象转换为字节数组并返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12052617/

相关文章:

python如何在不重复的情况下将新对象保存到列表中

memory - 将字符串转换为 &strs 时,切片和显式重新借用之间有区别吗?

python - python2.6中将整数转换为格式化的二进制字符串

c# - Windows Phone 8.1 MessageDialog 结果

c# - 使用 C# 将 png 文件转换为 pcx 文件

ios - 将数组保存到 userDefault

c++ - 为什么我需要 `std::type_identity_t` 来启用隐式类型转换?

c# - 在 C# 中,如果类或方法未标记为密封或虚拟,那是什么?

c# - 在哪里可以找到与 Dolphin 6100 设备交互的霍尼韦尔库?

javascript - sort(), sort(function(a,b){return a-b;}); 之间的区别和排序(函数(a,b){...})