[英]Pull SQL varbinary(max) to Xamarin image
我有一个 Xamarin 应用程序,它从 SQL 服务器数据库读取图像,保存图像数据索引的列是 4。
我创建了一个 class,其中包含一个名为 image 的成员,它是一个Image
object。
我有一个包含列表视图的内容页面。 在这个列表视图中,我有一个图像单元格。 所以,我想要的是从 SQL 服务器数据库中读取图像数据,使用阅读器,将当前正在读取的列转换为字节数组,然后将此字节数组转换为 memory ZF7B44CFAFD5C52223D5498 然后填充图像memory stream,然后listview中的图像将绑定到object中的图像,但看起来我无法做到这一点。 有什么帮助吗?
这是代码:
Class 文件:
internal class Attachments
{
public int serial { get; set; }
public string attachment_name { get; set; }
public byte[] image_stream { get; set; }
public string table_name { get; set; }
public DateTime create_date { get; set; }
public string related_serial { get; set; }
public string created_by { get; set; }
public Image class_image { get; set; } ? which one to use???
public StreamImageSource class_source { get; set; } ? which one to use???
}
Xaml 文件:
<ListView x:Name="images_lv" HasUnevenRows="True">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal">
<Image Grid.RowSpan="2"
Source="{Binding class_source}"
Aspect="AspectFill"
HeightRequest="60"
WidthRequest="60" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Xaml.cs
文件:
private async void get_image_from_db()
{
List<Classes.Attachments> attachments = new List<Classes.Attachments>();
string conn = "Server=******; database=******; user id=******; password=*****";
string query = "select * from Attachments";
SqlConnection connection = new SqlConnection(conn);
try
{
connection.Open();
SqlCommand cmd = new SqlCommand(query, connection);
SqlDataReader reader = cmd.ExecuteReader();
MemoryStream ms = new MemoryStream();
while (reader.Read())
{
ms.Position = 0;
int serial = reader.GetInt32(0);
string attachemnt_name = reader.GetString(1);
string table_name = reader.GetString(2);
DateTime createdate = reader.GetDateTime(3);
byte[] media = reader.GetSqlBytes(4).Value;
ms.Write(media,0, media.Length);
string related_serial = reader.GetString(5);
string created_by = reader.GetInt32(6).ToString() ;
attachments.Add(new Classes.Attachments
{
serial = serial,
attachment_name = attachemnt_name,
image_stream = media,
related_serial = related_serial,
created_by = created_by,
create_date = createdate,
class_source = (StreamImageSource)ImageSource.FromStream(() => ms),
class_image = new Image().Source()
//class_image.Source = ImageSource.FromStream(() => ms)
}) ;
}
images_lv.ItemsSource = attachments;
}
catch (Exception ex)
{
await DisplayAlert("", ex.ToString(), "");
}
}
谢谢你的帮助
没有理由使用中间字节[],并且在写入 MemoryStream 之后,您必须再次倒带 stream。
byte[] media = reader.GetSqlBytes(4).Value;
ms.Write(media,0, media.Length);
至
reader.GetStream(4).CopyTo(ms);
ms.Position=0;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.