2012-02-16 100 views
5

我的應用程序使用相機拍攝圖像並將其上傳到flickr。我想壓縮圖片,以便上傳不會像目前那樣長。我嘗試了BitmapSource和WriteableBitmap的'SaveJpeg'方法來完成這個,但失敗了。位圖源在Silverlight/WP中沒有與完整的.NET框架版本中相同的可用成員,並且WriteableBitmap一直給我提供'此流不支持寫入'錯誤的SaveJpeg方法。如何在Windows Phone上壓縮圖像

這是我目前在做我的CameraCaptureTask完成事件處理程序:

private void CameraCaptureCompleted(object sender, PhotoResult e) 
    { 
     if (e == null || e.TaskResult != TaskResult.OK) 
     { 
      return; 
     }                
     BitmapImage bitmap = new BitmapImage {CreateOptions = BitmapCreateOptions.None};       
     bitmap.SetSource(AppHelper.LoadImage(e.ChosenPhoto)); 
     WriteableBitmap writeableBitmap = new WriteableBitmap(bitmap); 

     // Encode the WriteableBitmap object to a JPEG stream. 
     writeableBitmap.SaveJpeg(e.ChosenPhoto, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight, 0, 85); 
    } 

此代碼給我:「流不支持寫入」錯誤。

有沒有其他一些方法可以壓縮圖像,還是必須編寫壓縮算法?

UPDATE FIXED !!

private void CameraCaptureCompleted(object sender, PhotoResult e) 
    { 
     if (e == null || e.TaskResult != TaskResult.OK) 
     { 
      return; 
     }                
     BitmapImage bitmap = new BitmapImage {CreateOptions = BitmapCreateOptions.None};       
     bitmap.SetSource(AppHelper.LoadImage(e.ChosenPhoto)); 
     WriteableBitmap writeableBitmap = new WriteableBitmap(bitmap); 

     // Encode the WriteableBitmap object to a JPEG stream. 
     writeableBitmap.SaveJpeg(new MemoryStream(), writeableBitmap.PixelWidth, writeableBitmap.PixelHeight, 0, 85); 
    } 

我正試圖寫入源碼流。衛生署!

謝謝。

+0

PhotoResult e不是一個流,因此SaveJpeg無法正常工作,您想在哪裏保存圖片? IsolatedStorage或臨時流或其他地方... – ameer 2012-02-16 22:19:43

+1

只要你知道,當你將它保存到新的MemoryStream()時,你現在沒有參考你現在保存的位置,最好先創建內存流,然後將它傳遞給內存流那麼一旦你獲得了壓縮文件,可以直接從存儲器流中上傳它,或者將其保存到獨立的存儲器中,然後再上傳。 – ameer 2012-02-16 22:45:20

回答

3

SaveJpeg是我想這樣做的方式。你也許可以用其他方式做,但我認爲這將是最簡單和最自然的。錯誤「此流不支持寫入」很可能是因爲您傳遞給SaveJpeg的任何流都不可寫。我不完全相信你正在嘗試寫,嘗試使用只是一個普通的老內存流,看看是否可行喜歡這樣

using System.IO; 

// ... 

MemoryStream ms = new MemoryStream(); 
pic.SaveJpeg(ms, pic.PixelWidth, pic.PixelHeight, 0, 0, 50); 

您可以調整在最後一個參數的質量。像素寬度/高度是從WriteableBitmap,所以如果你有其他的來源,你可能需要使用另一種方法/屬性來獲得寬度/高度。您可能想要縮放這些,因爲來自相機的圖片可能非常大。這取決於你上傳這些照片的內容,但是縮放它們還可以縮小文件的大小。

+0

謝謝你的回覆。我已經使用上面的代碼片段更新了我的帖子。這正是我目前所面臨的。 – Cranialsurge 2012-02-16 22:17:03