2016-12-27 63 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