内存中转换后的图像与存储后再读取时不一样

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

我有一个图像作为流传入,我正在尝试将传入的图像从任何可能的图像(即使它已经是 PNG)转换为 PNG。

我这样做是为了清理图像,因为它来自我不信任的来源。 通过转换它,我试图删除在存储图像之前可能已注入图像的任何代码,并在稍后将其返回到前端客户端。

我试图在记忆中做到这一点,据我所知,应该这样做:

Image image = Image.FromStream(stream, false, true);
using (MemoryStream ms = new MemoryStream())
{
    image.Save(ms, ImageFormat.Png);
    return ValidateImage(path, ms);
};

然而,我注意到,以上述方式执行此操作与将图像存储到磁盘,然后在我转换后再次读取它会产生不同的结果。

Image image = Image.FromStream(stream, false, true);
using (MemoryStream ms = new MemoryStream())
{
    image.Save(ms, ImageFormat.Png);
    File.WriteAllBytes(path, ms.ToArray());
};

using (FileStream fs = new FileStream(path, FileMode.Open))
{    
    return ValidateImage(path, fs);
};

我的 ValidateImage 方法有时会执行此操作:


byte[] bytes;
using (MemoryStream ms = new MemoryStream())
{
     contentStream.CopyTo(ms);
     bytes = ms.ToArray();
}

if(Validate(bytes)){
}

public override bool Validate(byte[] data)
{
     ImageFormat _format = new ImageFormat(new Guid("{b96b3caf-0728-11d3-9d7b-0000f81ef32e}"))
    try
    {
        // Try to open the image
        Image img;
        using (Stream ms = new MemoryStream(data))
        {
            img = Image.FromStream(ms);
        }

        // Check if the format matches the expected format
        return img.RawFormat.Equals(_format);
    }
    catch (Exception)
    {
        // Return false on exception
        return false;
    }
}

上面的 Validate() 返回 false,因为当我仅在内存中进行转换时,RawFormat 不等于 _format。当我将文件写入磁盘然后再次读入时,它返回 true,我想知道为什么,并希望找到一位能够启发我并帮助我仅在内存中正确进行转换的圣人。

提前谢谢您

c# image .net-4.8 file-conversion
1个回答
0
投票

在完成

Stream ms
之前,您正在将
Validate()
放入
img
中。当 ms
 还活着时,你
必须让
img
 活着

在将图像写入外部代码后,您还应该在外部代码中重置MemoryStream ms

的当前位置
,以便
ValidateImage()
看到它。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.