2016-12-09 2 views
2

나는 Azure에서 데이터베이스를 설정하고 다른 데이터 유형과 함께 일부 사진을 저장합니다. 사진을 보유 할 열은 이미지 데이터 유형입니다. 이 (이진 파일에 그림을 변환)처럼 내 삽입Azure 데이터베이스 및 사진

public void Insert()  
    { 
    string filepath = "C:\\PictureFolder\\MyPhoto.jpg"; 
    byte[] Pic = File.ReadAllBytes(filepath); 

    DataContex oDc = new DataContex(); 

    tblShip otblShip = new tblShip; 

    otblShip.Id = Guid.NewGuid(); 
    otblShip.Name = "Enterprise"; 
    otblShip.Picture = Pic; 

    oDc.tblShips.InsertOnSubmit(oMyTable); 

    oDc.SubmitChanges(); 

    } 

삽입 내가 푸른 내 테이블을 검사 할 때, 이진 값은 그림 컬럼에 삽입되어, 작동 보인다. 어떻게 다시 가져올 수 있으며 WPF 인터페이스에 실제 사진을 표시하려면 어떻게해야합니까?

+0

이미지를 Blob 저장소에 저장하고 해당 ID 또는 경로를 데이터베이스에 저장하면됩니다. 저장 비용은 저렴합니다. – CSharpRocks

답변

0

이미 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; 
    } 
} 

당신은 확실히 같은 결과를 얻을 수 있습니다,하지만 당신은 지금이 발전함에 따라보다 쉽게 ​​유지 관리 할 수 ​​있도록하는 매우 잘 분리 된 응용 프로그램을 가지고, 그 이미지는 다음과 같이 구현 될 수로드합니다.

희망이 도움이됩니다.

+0

.AsNoTracking()은 빨간색 물결 모양을 나타내며 어셈블리 참조 또는 지시문을 요청합니다. System.Data.Entity를 추가했습니다. System.Data.Linq; 아직 안돼. – Coolhand

+0

@Coolhand이 경우이 줄을 안전하게 제거 할 수 있습니다. 다른 종류의 datacontext를 사용하는 것처럼 보일 때 EF DbContext를 사용하여 테스트했습니다. –

+0

내 DataContext 내 dbml에서입니다. 나는 EF DbContext가 무엇인지 모른다. – Coolhand

0

모든 것이 여기에 하드 코딩되었지만, 여기서 어떻게 100 x 100 픽셀 이미지를 이동시키는가입니다. Db에서부터 그리고 Db로. 이미지를 저장할 수있는 더 좋은 방법이 있다는 것을 이해합니다. 그러나 제 목적을 위해이 방법은 훌륭합니다!

 public void InsertPhotoToDb() 
    { 
     string filepath = "C:\\TFS\\Enterprise.jpg"; 
     byte[] Pic = File.ReadAllBytes(filepath); 

     ArmadaDataContext oDc = new ArmadaDataContext(); 

     tblPictureTest otblPictureTest = new tblPictureTest(); 
     otblPictureTest.Id = Guid.NewGuid(); 

     otblPictureTest.FileName = "Enterprise"; 
     otblPictureTest.Photo = Pic; 
     oDc.tblPictureTests.InsertOnSubmit(otblPictureTest); 
     oDc.SubmitChanges(); 

     oDc = null; 
    } 

    private void DisplayImageFromDb() 
    { 
     using (var oDc = new ArmadaDataContext()) 
     { 
      var item = oDc 
       .tblPictureTests 
       .FirstOrDefault(x => x.FileName == "Enterprise"); // Retrieves using the filename 


      // If retrieving using the GUID, use the line below instead. 
      // .FirstOrDefault(x => x.Id == Guid.Parse("58b44a51-0627-43fe-9563-983aebdcda3a")); 


      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.Photo.ToArray()); 
      img.BeginInit(); 
      img.StreamSource = ms; 
      img.EndInit(); 

      //assign the image to the Source property of the Image box in the UI. 
      imgPhoto.Source = img; 
     } 
    }