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

问题描述 投票:0回答:1

我已将一个图像(.tif图像)转换为字节数组并保存在数据库中。我现在正在从数据库中检索该字节数组,并希望再次转换为图像,但是我将其转换回图像的该字节数组却无法产生相同的图像。作为测试(如下所示),出于测试目的,我仅使用图像而不从数据库读取数据。

从图像到字节数组的初始转换:

//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);

现在尝试转换回图像,我正在执行以下操作:

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

但是似乎结果不一样。我有一个“拆分”功能,可在tiff中拆分页面,其中一个返回8个页面(位图),另一个仅返回1。

我对上述内容了解不多,所以需要一些帮助来填补知识空白:)

感谢您的帮助!

c# arrays image-processing memorystream
1个回答
1
投票

我找到了一个最终可以解决的解决方案。似乎在完成初始ImageToByteArray时,它仅在执行“第一页”而不是全部8。因此,我使用以下代码转换了整个tiff图像:

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

然后我使用以下内容转换回图像(response是从我们的byte[]返回的API:]

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
            }

我读到要使上面的内容起作用(并对其进行了测试),对byte[]所做的任何操作都必须在using内完成,因为using意味着image被放置。

© www.soinside.com 2019 - 2024. All rights reserved.