所以我从FTP服务器下载图像,然后尝试在我的Android设备上本地保存它。我正在使用的代码以前没有任何变化,应该影响它下载和处理随机停止工作的图像的方式。流填充字节数组就好了,但无论出于何种原因,bitmapfactory都无法对其进行解码。这是一个普通的图像文件,其标题中恰好有空格和数字符号,但这不应该有任何影响。这是相关的代码:
BufferedInputStream input = new BufferedInputStream(dataSocket.InputStream);
byte[] buffer = new byte[fileSize];
int bytesRead = 0;
while ((bytesRead = input.Read(buffer)) != -1)
{
input.Read(buffer, 0, bytesRead);
}
if (ASCII)
{
String result = System.Text.ASCIIEncoding.ASCII.GetString(buffer);
System.IO.File.WriteAllText(savePath, result);
} else
{
Bitmap bm = Android.Graphics.BitmapFactory.DecodeByteArray(buffer, 0, buffer.Length);
//FileOutputStream fos = new FileOutputStream(savePath);
Android.Graphics.Bitmap.CompressFormat format = null;
String extension = System.IO.Path.GetExtension(filename);
switch (System.IO.Path.GetExtension(filename))
{
case ".jpg":
case ".jpeg":
case ".jpe":
format = Android.Graphics.Bitmap.CompressFormat.Jpeg;
break;
case ".png":
case ".bmp":
case ".gif":
case ".tif":
case ".tiff":
format = Android.Graphics.Bitmap.CompressFormat.Png;
break;
}
bm.Compress(format, 100, System.IO.File.OpenWrite(savePath));
//BufferedOutputStream fileOut = new BufferedOutputStream(System.IO.File.OpenWrite(savePath));
//fileOut.Write(buffer);
//fileOut.Flush();
//fileOut.Close();
}
一个空引用异常在行bm.Compress上触发(格式...由于BitMapFactory.DecodeByteArray()返回null。我无法弄清楚为什么它在之前的工作之后随机开始这样做。它实际上已经工作了开始返回null然后再次开始工作然后再次停止工作,但我不知道我能改变什么会影响任何事情。