이미 Azure를 사용하고 있으므로 @CSharpRocks에 동의합니다. BlobStorage 스토리지 계정에 사진을 저장하고 연구하는 것이 매우 편리 할 것입니다. 저장소 계정은 기존의 데이터베이스 저장소와 비교할 때 많은 장점이 있습니다.
스토리지 계정 및 시작 방법에 대한 자세한 내용은 here을 참조하십시오.
하지만이 질문은 자신의 질문에 따라 이미지를 검색하여 WPF 응용 프로그램에 표시하는 방법에 대한 것입니다. 그래서 보자 :
을 이미 당신이 이미지를 데이터베이스에 저장, 그래서 당신은 기본 키 값 (또는 다른 쿼리)를 사용하여 관련 tblShip
개체를 가져올 수 있습니다 :이 곳에서이 가정
을 당신의 XAML보기 :
<Image Name="imgControl" ... />
당신은이 같은 이미지를 보여줄 수 :
private void DisplayImageFromDb(Guid id)
{
using (var context = new DataContext())
{
var item = context
.tblShips
.AsNoTracking()
.FirstOrDefault(x => x.Id == id);
if (item == null)
throw new Exception("Image could not be found!");
//Convert the byte[] to a BitmapImage
BitmapImage img = new BitmapImage();
MemoryStream ms = new MemoryStream(item.Picture);
img.BeginInit();
img.StreamSource = ms;
img.EndInit();
//assign the image to the Source property of the Image Control.
imgControl.Source = img;
}
}
,536,
괜찮습니다.하지만 더 많은 WPF (MVVM) 지향적 인 방법을 사용하면 더 좋을 것입니다. 자, xaml 뷰를 가지고 있지만 MVVM을 사용하고 있다고 가정 해 봅시다. 이미지 컨트롤은 따라서 뷰 모델 속성에 바인딩된다
using System;
using System.Globalization;
using System.IO;
using System.Windows.Data;
using System.Windows.Media.Imaging;
namespace WpfApp1
{
public class ByteArrayToImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null) return null;
//Convert the byte[] to a BitmapImage
BitmapImage img = new BitmapImage();
MemoryStream ms = new MemoryStream((byte[])value);
img.BeginInit();
img.StreamSource = ms;
img.EndInit();
return img;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
:
다음
<Windows.Resources>
<local:ByteArrayToImageConverter x:Key="ByteArrayToImageConverter" />
</Window.Resources>
는 컨버터의 구현 :보기의 자원에
<Image Grid.Row="1"
Source="{Binding ImageSource, Converter={StaticResource ByteArrayToImageConverter}}"/>
당신이 변환기를 선언
이제는 UI를 실제로 분리 했으므로 걱정을 완전히 분리했습니다. 이미지를 howing 당신의 ViewModel는 데이터베이스에서로드 및 도메인 개체를 조작해야합니다
바인딩에 사용 ImageSource 속성을 선언해야합니다 귀하의 ViewModel : 모든 리팩토링 후
private byte[] imageSource;
public byte[] ImageSource
{
get { return imageSource; }
set
{
imageSource = value;
//must implement property changed notifications
OnPropertyChanged(new PropertyChangedEventArgs("ImageSource"));
}
}
를, 뷰 모델의 방법
private void DisplayImageFromDb(int id)
{
using (var context = new DataContext())
{
var item = context
.tblShips
.AsNoTracking()
.FirstOrDefault(x => x.Id == id);
if (item == null)
throw new Exception("Image could not be found!");
//Assign the property and let the binding do the work
ImageSource = item.Picture;
}
}
당신은 확실히 같은 결과를 얻을 수 있습니다,하지만 당신은 지금이 발전함에 따라보다 쉽게 유지 관리 할 수 있도록하는 매우 잘 분리 된 응용 프로그램을 가지고, 그 이미지는 다음과 같이 구현 될 수로드합니다.
희망이 도움이됩니다.
이미지를 Blob 저장소에 저장하고 해당 ID 또는 경로를 데이터베이스에 저장하면됩니다. 저장 비용은 저렴합니다. – CSharpRocks