2016-07-26 99 views
0

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

回答

0

一个PNG总是以0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A字节开头。

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

在API上,您应该评论您的代码并使用好的方法名称来防止错误。您可以从ImageToBinaryPngImageToBinary改变你的方法名称...

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; 
} 
+0

ImageToBinary功能在Web API中用来生成将发送到其它应用程序中的byte [],所以我一直在寻找一种方法,我可以确保在其他应用程序中收到字节[]时,不能将其转换为任何其他格式,只能使用PNG格式。 – Dineesh

相关问题