【发布时间】:2020-01-03 15:16:46
【问题描述】:
我正在尝试显示来自数据库的 varbinary 图像,我正在使用此代码将其转换为 byte[]
Film.cs
if (row["foto"] != DBNull.Value)
f.Foto = (byte[])row["foto"];
这就是我选择要发送到数据库的文件的方式
GestaoDeFilmesViewModel.cs
public async static Task<StorageFile> OpenLocalFile(params string[] types)
{
var picker = new FileOpenPicker();
picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
Regex typeReg = new Regex(@"^\.[a-zA-Z0-9]+$");
foreach (var type in types)
{
if (type == "*" || typeReg.IsMatch(type))
picker.FileTypeFilter.Add(type);
else
throw new InvalidCastException("A extensão do ficheiro está incorreta");
}
var file = await picker.PickSingleFileAsync();
if (file != null)
return file;
else
return null;
}
然后像这样发送它
GestaoDeFilmesViewModel.cs
public async Task<bool> UpdateFoto(StorageFile file)
{
if (file == null)
return false;
SelectedFilme.Foto = (await FileIO.ReadBufferAsync(file)).ToArray();
if(SelectedFilme.Foto == null)
{
return false;
}
if (SelectedFilme.UpdateFoto() == 1)
{
return true;
}
return false;
}
这是我用来将图像从 byte[] 转换为 BitMapImage 的用户控件
FotoControl.xaml
<Page
x:Class="MyMovies.universal.UserControl.FotoControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MyMovies.universal.UserControl"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid>
<Image x:Name="Foto"></Image>
</Grid>
</Page>
这是后面的代码,Source_Changed方法中抛出了一个异常,我会发布一个关于它的图片
FotoControl.xaml.cs
public sealed partial class FotoControl : UserControl
{
public FotoControl()
{
this.InitializeComponent();
}
public byte[] ImageSource
{
get { return (byte[])GetValue(ImageSourceProperty); }
set { SetValue(ImageSourceProperty, value); }
}
public static readonly DependencyProperty ImageSourceProperty =
DependencyProperty.Register("ImageSource", typeof(byte[]), typeof(UserControlFolder.FotoControl), new PropertyMetadata(null, new PropertyChangedCallback(Source_Changed)));
private static async void Source_Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (e.NewValue != null && e.NewValue is byte[] data)
{
var instance = d as FotoControl;
BitmapImage image = new BitmapImage();
using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
{
await stream.WriteAsync(data.AsBuffer());
await image.SetSourceAsync(stream);
}
instance.Foto.Source = image;
}
}
}
这是我在转换后显示图像的页面
GestaoDeFilmes.xaml
<control:FotoControl ImageSource="{Binding Foto, Mode=TwoWay}"/>
您可以通过调试图像看到 Foto 有内容,不为空。 我认为该异常与 Windows 无法从其他人所说的内容中解码图像有关。 提前致谢。
【问题讨论】:
-
你能翻译异常信息吗?并且直接在问题中写出来,不只是在屏幕上?
-
请查看this。你好像很想念
stream.Seek(0); -
对不起,我忘记翻译了
-
非常感谢@NicoZhu-MSFT,它成功了,你能把它作为答案发布吗?所以我可以接受答案来帮助其他有同样问题的人吗?谢谢