所以,我有以下脚本将图像转换为二进制文件(所以我可以把它放在blob上):
public static byte[] ImagemBin(string imagePath, int imagem_comp)
{
FileStream fileStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[imagem_comp];
int numBytesToRead = imagem_comp;
int numBytesRead = 0;
while (numBytesToRead > 0)
{
// Read may return anything from 0 to numBytesToRead.
int n = fileStream.Read(buffer, numBytesRead, numBytesToRead);
// Break when the end of the file is reached.
if (n == 0)
break;
numBytesRead += n;
numBytesToRead -= n;
}
numBytesToRead = buffer.Length;
fileStream.Read(buffer, 0, numBytesToRead);
fileStream.Close();
return buffer;
}
其中imagePath是计算机中图像的位置,imagem_comp是图像的大小。但是,图像转换是不完整的,在几个字节之后,它返回唯一的0 ...
那么,对此有何帮助?
提前谢谢。
答案 0 :(得分:0)
你应该解释你想要完成的事情。喜欢imagem_comp
应该是什么?我发现你的逻辑存在以下错误。
numBytesToRead -= n;
上要读取的字节数中减去读取的字节数。一次读取后,您将只需要读取0个字节。imagem_comp
,则返回的缓冲区不包含所有数据。正如@ bmm6o在上面的评论中所述,您应该能够将其替换为File.ReadAllBytes。
答案 1 :(得分:0)
它似乎适用于此版本:
public static byte[] ImagemBin(string imagePath, int imagem_comp)
{
FileStream fileStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[imagem_comp];
int numBytesToRead = imagem_comp;
int numBytesRead = 0;
while (numBytesToRead > 0)
{
// Read may return anything from 0 to numBytesToRead.
int n = fileStream.Read(buffer, numBytesRead, numBytesToRead);
// Break when the end of the file is reached.
if (n == 0)
break;
numBytesRead += n;
numBytesToRead -= n;
}
fileStream.Close();
return buffer;
}
即。删除行:
numBytesToRead = buffer.Length;
和
fileStream.Read(buffer, 0, numBytesToRead);
那就是说,我同意别人提到的内容;考虑使用ReadAllBytes。 : - )