简体   繁体   English

将字节数组转换为 C# 中的图像

[英]Converting byte array to image in C#

I have converted an image(.tif image) to a byte array and saved in the DB.我已将图像(.tif 图像)转换为字节数组并保存在数据库中。 I am now retrieving that byte array from the DB and want to convert to an image again, but this byte array I am converting back to an image, is not producing the same.我现在正在从数据库中检索该字节数组并希望再次转换为图像,但是我正在转换回图像的这个字节数组并没有产生相同的结果。 As a test (as below), I am only using the image and not reading from the DB, for testing purposes.作为测试(如下所示),出于测试目的,我仅使用图像而不是从数据库中读取数据。

The initial convert from Image to byte array:从 Image 到字节数组的初始转换:

//This is the function I am using:
public static byte[] ImageToByteArray(Image image)
        {
            using (var ms = new MemoryStream())
            {
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Tiff);
                return ms.ToArray();
            }
        }

//Converting to byte array:
var tifImage = Image.FromFile(file.ToString());
var imageContent = ImageToByteArray(tifImage);

Now to try and convert back to an Image, I am doing the following:现在尝试转换回图像,我正在执行以下操作:

var ms = new MemoryStream(imageContent);
var test1 = Image.FromStream(ms);

But it seems the results are not the same.但结果似乎不太一样。 I have a "Splitting" function that splits the pages within the tiff, and the one returns 8 pages(bitmaps) and the other just 1.我有一个“拆分”功能,可以拆分 tiff 中的页面,一个返回 8 个页面(位图),另一个返回 1 个。

I dont know much about the above, so need a little help in filling in the knowledge gaps, please :)我对上述内容不太了解,所以需要一点帮助来填补知识空白,请:)

Thanks for any the help!感谢您的帮助!

I found a solution that ended up working.我找到了一个最终有效的解决方案。 It seems that when the initial ImageToByteArray was being done, it was only doing the "1st page" and not all 8. So I used the following code to convert the whole tiff image:似乎在完成初始ImageToByteArray时,它只执行“第一页”而不是全部 8。所以我使用以下代码来转换整个 tiff 图像:

var tiffArray = File.ReadAllBytes(file); //The `file` is the actual `.tiff` file

I then used the following to convert back to an image(The response is a byte[] returned from our API ):然后我使用以下内容转换回图像( response是从我们的API返回的byte[] ):

using (MemoryStream ms = new MemoryStream(response))
            {
                ms.Position = 0;
                Image returnImage = Image.FromStream(ms);

                var splitImages = ImageHelper.Split(returnImage);//This is to split the pages within the tiff
            }

I read that for the above to work(and I tested it), anything you do to the byte[] you are converting back to an image, must be done within the using , as anything after the using means the image is disposed.我读到要使上述工作(并且我对其进行了测试),您对要转换回图像的byte[]所做的任何事情都必须在using内完成,因为在using之后的任何using意味着image已被处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM