2014-03-07 2 views
0

url에서 다운로드 한 BitmapImage를 app StorageFolder에 저장하려고합니다. 나는 나를 위해 테 이미지를 저장하는 함수를 만들려고 노력했다.C# Windows Phone 8 BitmapImage를 StorageFolder에 저장하는 방법

public async Task<string> savePhotoLocal(BitmapImage photo, string photoName) 
    { 
     var profilePictures = await storageRoot.CreateFolderAsync("profilePictures", CreationCollisionOption.OpenIfExists); 
     var profilePicture = await profilePictures.CreateFileAsync(photoName+".jpg", CreationCollisionOption.ReplaceExisting); 

     byte[] byteArray = new byte[0]; 
     using (MemoryStream stream = new MemoryStream()) 
     { 
      using (Stream outputStream = await profilePicture.OpenStreamForWriteAsync()) 
      { 
       await stream.CopyToAsync(outputStream); 
      } 
     } 

     return profilePicture.Path; 
    } 

하지만이 작동하지 않습니다와 나는 다시 오류를하지 않기 때문에 여기에서 잘못가는 뭐죠 내가 정말 모르는 : 이것은 내가 지금까지 무엇을 가지고 있습니다. 어떤 도움이나 코드 샘플도 좋을 것입니다. 다음

linkRequest = (HttpWebRequest)WebRequest.Create(uri); 
linkRequest.Method = "GET"; 
WebRequestState webRequestState = new WebRequestState(linkRequest, additionalDataObject); 
linkRequest.BeginGetResponse(client_DownloadImageCompleted, webRequestState); 

과 :

는 HttpWebRequest를 통해 이미지를 다운로드 :

답변

0
public async Task<string> savePhotoLocal(BitmapImage photo, string photoName) 
    { 
     string folderName ="profilePictures"; 
     var imageName =photoName+".jpg";   
     Stream outputStream = await profilePictures.OpenStreamForWriteAsync(); 
     if(outputStream!=null) 
      { 
      this.SaveImages(outputStream,folderName,imageName); 
      } 
     return imageName ; 
    } 





private void SaveImages(Stream data, string directoryName, string imageName) 
      { 
IsolatedStorageFile StoreForApplication =IsolatedStorageFile.GetUserStoreForApplication(); 
       try 
       { 
        using (MemoryStream memoryStream = new MemoryStream()) 
        { 
         data.CopyTo(memoryStream); 
         memoryStream.Position = 0; 
         byte[] buffer = null; 
         if (memoryStream != null && memoryStream.Length > 0) 
         { 
          BinaryReader binaryReader = new BinaryReader(memoryStream); 
          buffer = binaryReader.ReadBytes((int)memoryStream.Length); 
          Stream stream = new MemoryStream(); 
          stream.Write(buffer, 0, buffer.Length); 
          stream.Seek(0, SeekOrigin.Begin); 
          string FilePath = System.IO.Path.Combine(directoryName, imageName); 
          IsolatedStorageFileStream isoFileStream = new IsolatedStorageFileStream(FilePath, FileMode.Create, StoreForApplication); 
          Deployment.Current.Dispatcher.BeginInvoke(() => 
           { 
            BitmapImage bitmapImage = new BitmapImage { CreateOptions = BitmapCreateOptions.None }; 
            bitmapImage.SetSource(stream); 
            WriteableBitmap writeableBitmap = new WriteableBitmap(bitmapImage); 
            writeableBitmap.SaveJpeg(isoFileStream, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight, 0, 100); 
           }); 
         } 
        } 

       } 
       catch (Exception ex) 
       { 
        //ExceptionHelper.WriteLog(ex); 
       } 
      } 
+0

빠른 응답 주셔서 감사하지만 profilePicture 당신이 스트림에 대한 열려고하면 그 문자열이 불가능합니다. – apero

+1

StoreForApplication을 설명해 주시겠습니까? 나는 이것에 대한 오류를 얻는다. 그것은 IsolatedStorageFile isf를 요구하지만, 이것이 무엇인지 전혀 모른다. – apero

0

이 시도

private void client_DownloadImageCompleted(IAsyncResult asynchronousResult) 
     { 
      Deployment.Current.Dispatcher.BeginInvoke(() => 
      { 
        WebRequestState webRequestState = asynchronousResult.AsyncState as WebRequestState; 

        AdditionalDataObject file = webRequestState._object; 

        using (HttpWebResponse response = (HttpWebResponse)webRequestState.Request.EndGetResponse(asynchronousResult)) 
        { 
         using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication()) 
         { 
            using (Stream stream = response.GetResponseStream()) 
            { 

             BitmapImage b = new BitmapImage(); 

             b.SetSource(stream); 
             WriteableBitmap wb = new WriteableBitmap(b); 
             using (var isoFileStream = isoStore.CreateFile(yourImageFolder + file.Name)) 
             { 
              var width = wb.PixelWidth; 
              var height = wb.PixelHeight; 
              System.Windows.Media.Imaging.Extensions.SaveJpeg(wb, isoFileStream, width, height, 0, 100); 
             } 
            } 
         } 
       } 
       }); 
     } 

그리고 WebRequestState 클래스는 다음과 같습니다

public class WebRequestState 
    { 
     public HttpWebRequest Request { get; set; } 
     public object _object { get; set; } 



     public WebRequestState(HttpWebRequest webRequest, object obj) 
     { 
      Request = webRequest; 
      _object = obj; 
     } 
    } 
+0

응답 해 주셔서 감사합니다. 그러나 나는 여전히 작동하도록 코드를 얻지 못했습니다. 나는 이것에서 새롭다. additionalDataObject가 무엇이고 거기에 무엇을 넣어야하는지 설명해 주시겠습니까? 지금 오류가 발생합니다. – apero

+0

아, 예. 그건 내 오래된 코드 일 뿐이야. additionalDataObject 대신 이미지 이름이 포함 된 문자열 객체를 전송할 수 있습니다. 그러면 webRequestState에서 가져올 수 있습니다. (string filename = (string) webRequestState._object;) – Olter