限制图像字节数组转换为PNG格式



我有一个Web API,它从文件夹中获取图像(可以是jpeg或png),并将其转换为字节数组并发送到调用应用程序。

我使用以下函数将图像转换为二进制:

public static byte[] ImageToBinary(string imagePath)
{
    FileStream fS = new FileStream(imagePath, FileMode.Open, FileAccess.Read);
    byte[] b = new byte[fS.Length];
    fS.Read(b, 0, (int)fS.Length);
    fS.Close();
    return b;
}

下面的"数据"将传递给Web API响应。

byte[] data = ImageToBinary(<PATH HERE>);

我想要的是限制这个"数据"只能在调用这个Web API的应用程序中转换为PNG格式。

目的是,我不想每次都提醒正在编写其他应用程序的其他开发人员,您只需要将其转换为PNG。

PNG始终以0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A字节开头。

因此,您可以检查文件的第一个字节和扩展名。

在API上,您应该注释代码并使用好的方法名称来防止错误。您可以将方法名称从ImageToBinary更改为PngImageToBinary。。。

public static readonly byte[] PngSignature = { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A };
/// <summary>
/// Convert a PNG from file path to byte array.
/// </summary>
/// <param name="imagePath">A relative or absolute path for the png file that need to be convert to byte array.</param>
/// <returns>A byte array representation on the png file.</returns>
public static byte[] PngImageToBinary(string imagePath)
{
    if (!File.Exists(imagePath)) // Check file exist
        throw new FileNotFoundException("File not found", imagePath);
    if (Path.GetExtension(imagePath)?.ToLower() != ".png") // Check file extension
        throw new ArgumentOutOfRangeException(imagePath, "Requiere a png extension");
    // Read stream
    byte[] b;
    using (var fS = new FileStream(imagePath, FileMode.Open, FileAccess.Read))
    {
        b = new byte[fS.Length];
        fS.Read(b, 0, (int)fS.Length);
        fS.Close();
    }
    // Check first bytes of file, a png start with "PngSignature" bytes
    if (b == null
        || b.Length < PngSignature.Length
        || PngSignature.Where((t, i) => b[i] != t).Any())
        throw new IOException($"{imagePath} is corrupted");
    return b;
}