이미지를 불러올 경우
가장 간단한 코드는 다음과 같다.
1)
BitmapImage img = new BitmapImage(new Uri(myUri));
Image.Source = img;
검색하다보니 이 코드를 포함해서 여러 개의 코드 조각들 간의
이미지 로딩 속도를 비교한 결과가 있는 블로그가 있었다.
(http://lovehana.com/flyingmt/566?category=8)
위의 블로그에서 가장 속도가 좋다고 나온 코드 조각은 다음과 같다.
2)
BitmapImage img = new BitmapImage();
img.BeginInit();
img.CacheOption = BitmapCacheOption.OnDemand;
img.CreateOptions = BitmapCreateOptions.DelayCreation;
img.DecodePixelWidth = 300;
img.UriSource = new Uri(myUri);
img.EndInit();
Image.Source = img;
단, 2) 번 코드의 문제는 web 상의 이미지는 로드할 수 없다(http:// ... 주소로 된 이미지)
위의 1), 2) 번 코드는 프로세스가 이미지를 사용하고 있어
해당 프로세스나 다른 프로세스에서 해당 이미지를 변경할 수 없다.
즉 이미지를 로드하여 이를 편집하고 덮어쓰기 를 하거나 하는 경우에는 사용할 수 없다.
따라서 이런 경우에는 다음과 같은 코드를 사용한다.
3)
Byte[] buffer;
if (myUri.Substring(0, 4).Equals("http"))
{
WebClient wc = new WebClient();
buffer = wc.DownloadData(new Uri(myUri, UriKind.Absolute));
wc.Dispose();
}
else
{
buffer = System.IO.File.ReadAllBytes(myUri);
}
MemoryStream ms = new MemoryStream(buffer);
BitmapImage img = new BitmapImage();
img.BeginInit();
img.CacheOption = BitmapCacheOption.OnLoad;
img.StreamSource = ms;
img.EndInit();
Image.Source = img ;
'Dev > WPF' 카테고리의 다른 글
[WPF] Adorner (0) | 2012.07.31 |
---|---|
[WPF] Clipboard (클립보드) (0) | 2012.07.30 |
[WPF] Animated ScrollViewer (스크롤뷰어 애니메이션 적용) (0) | 2012.07.26 |
[WPF] Add WPF item entries in VS2010 (VS2010에서 WPF Item 추가하기) (0) | 2012.07.26 |