【发布时间】:2015-09-17 23:53:20
【问题描述】:
我正在开发一个向浏览器返回位图图像的自托管 WPF 应用程序(使用 Owin)。
我的控制器代码如下所示:
public ImageSource GetmbTiles(string FILE, string Z, string X, string Y)
{
string mbtiles = string.Format(("C:\\{0}.mbtiles"), FILE);
string connString = string.Format("Data Source={0}", mbtiles);
using (SQLiteConnection conn = new SQLiteConnection(connString))
{
System.Text.StringBuilder Query = new System.Text.StringBuilder();
Query.Append("SELECT tile_data ");
Query.Append("FROM tiles ");
Query.Append(string.Format("where zoom_level={0} and tile_column={1} and tile_row={2} ", Z, X, Y));
using (SQLiteCommand cmd = new SQLiteCommand(Query.ToString(), conn))
{
conn.Open();
using (SQLiteDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
buffer = GetBytes(dr);
}
}
}
}
//return new System.IO.MemoryStream(buffer);
return byteArrayToImage(buffer);
}
private static BitmapImage byteArrayToImage(byte[] imageData)
{
if (imageData == null || imageData.Length == 0) return null;
var image = new BitmapImage();
using (var mem = new MemoryStream(imageData))
{
mem.Position = 0;
image.BeginInit();
image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = null;
image.StreamSource = mem;
image.EndInit();
}
image.Freeze();
return image;
}
private static byte[] GetBytes(SQLiteDataReader reader)
{
const int CHUNK_SIZE = 2 * 1024;
byte[] buffer = new byte[CHUNK_SIZE];
long bytesRead = 0;
long fieldOffset = 0;
using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
{
bytesRead = reader.GetBytes(0, fieldOffset, buffer, 0, buffer.Length);
while (bytesRead == buffer.Length)
{
stream.Write(buffer, 0, Convert.ToInt32(bytesRead));
fieldOffset += bytesRead;
bytesRead = reader.GetBytes(0, fieldOffset, buffer, 0, buffer.Length);
}
stream.Write(buffer, 0, Convert.ToInt32(bytesRead));
return stream.ToArray();
}
}
当我从浏览器调用这个控制器时,我只得到一个 json 文件而不是图像。
异常消息是
<ExceptionMessage>Type 'System.IO.MemoryStream' with data contract name 'MemoryStream:http://schemas.datacontract.org/2004/07/System.IO' is not expected. Consider using a DataContractResolver if you are using DataContractSerializer or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to the serializer.</ExceptionMessage>
我是 Web 开发人员,对 WPF 世界很陌生,所以请原谅这个菜鸟问题。但是到目前为止,无论我尝试返回图像都无济于事。我可以看到正在填充字节数组。但是字节数组不会显示在浏览器中,是否有一些我缺少的转换?任何提示或帮助将不胜感激。
【问题讨论】:
-
byteArrayToImage在做什么? -
@Clemens 我已经更新了我的代码。谢谢...
标签: c# wpf owin self-hosting