2016-12-27 61 views
0

的我已經讀了很多關於調整圖像大小和質量的減少對堆棧的職位,但其中的非已約降低質量以一定的物理磁盤空間C#StorageFile圖像尺寸調整到一定量的字節

我有一個代碼拍照:

private async void TakeAPhoto_Click(object sender, RoutedEventArgs e) 
{ 
    CameraCaptureUI captureUI = new CameraCaptureUI(); 
    captureUI.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg; 

    StorageFile photo = await captureUI.CaptureFileAsync(CameraCaptureUIMode.Photo); 
    if (photo != null) 
    { 

    } 
} 

現在我需要將數據發送到服務器,但在此之前,我需要保證照片不超過3 MB。

所以我這樣做:

BasicProperties pro = await photo.GetBasicPropertiesAsync(); 
if (pro.Size < 3072) 
{ 
    // SEND THE FILE TO SERVER 
} 
else 
{ 
    // DECREASE QUALITY BEFORE SENDING 
} 

所以現在的問題是關於else塊

有沒有更好的或者也許我錯過了一些內置的方法,以適應圖像到一定量兆字節通過降低質量?

因爲這樣做:

while (pro.Size <= 3072) 
{ 
    photo = // some logic to decrease quality on 10% 
} 

不真好看。

+0

我不認爲這是一個好得多的方法。是的,您可以應用一些啓發式方法(比如,如果文件比您需要的大得多 - 將質量降低10%以上),但仍然會出現循環和多個質量降低(如果降低質量無助於縮小尺寸) 。 – Evk

回答

0

只是創建一個功能:

/// <summary> 
    /// function to reduce image size and returns local path of image 
    /// </summary> 
    /// <param name="scaleFactor"></param> 
    /// <param name="sourcePath"></param> 
    /// <param name="targetPath"></param> 
    /// <returns></returns> 
    private string ReduceImageSize(double scaleFactor, Stream sourcePath, string targetPath) 
    { 
     try 
     { 
      using (var image = System.Drawing.Image.FromStream(sourcePath)) 
      { 
       //var newWidth = (int)(image.Width * scaleFactor); 
       //var newHeight = (int)(image.Height * scaleFactor); 


       var newWidth = (int)1280; 
       var newHeight = (int)960; 

       var thumbnailImg = new System.Drawing.Bitmap(newWidth, newHeight); 
       var thumbGraph = System.Drawing.Graphics.FromImage(thumbnailImg); 
       thumbGraph.CompositingQuality = CompositingQuality.HighQuality; 
       thumbGraph.SmoothingMode = SmoothingMode.HighQuality; 
       thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic; 
       var imageRectangle = new System.Drawing.Rectangle(0, 0, newWidth, newHeight); 
       thumbGraph.DrawImage(image, imageRectangle); 
       thumbnailImg.Save(targetPath, image.RawFormat); 
       return targetPath; 



      } 
     } 
     catch (Exception e) 
     { 
      Console.WriteLine("Exception in ReduceImageSize" + e); 
      return ""; 
     } 
    } 

然後再調用這個函數在其他塊下面你會得到相同的圖像與縮小的尺寸:

 string ImageLink = "https://imagesus-ssl.homeaway.com/mda01/337b3cbe-80cf-400a-aece-c932852eb929.1.10"; 
     string [email protected]"F:\ReducedImage.png"; 
     HttpWebRequest imageRequest = (HttpWebRequest)WebRequest.Create(ImageLink); 
     WebResponse imageResponse = imageRequest.GetResponse(); 
     Stream responseStream = imageResponse.GetResponseStream(); 

     string ImagePath= ReduceImageSize(0.5, responseStream, FinalTargetPath); 
+0

感謝您的尺寸縮小代碼,但有趣的主要部分,如果我有可能擺脫這一點: while(pro.Size <= 3072) { photo = //一些邏輯降低10% } 您的硬編碼代碼通過調整圖像大小來降低圖像的質量,但如果我的圖像將是20 MB - 輸出是3還是更少?不,所以我將不得不重新調整大小等。 – Cheese