![](/img/trans.png)
[英]reduce image size in bytes without resize and quality lose in c#
[英]C# StorageFile image resize to certain amount of bytes
我已經在Stack上閱讀了很多有關調整圖像大小和降低質量的文章,但是沒有一篇關於降低某些物理磁盤空間的質量的文章。
我有一個拍照的代碼:
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%
}
看起來真的不太好。
只需創建一個功能:
/// <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 "";
}
}
然后在您的else塊中調用此函數,如下所示,您將獲得相同大小的圖像:
string ImageLink = "https://imagesus-ssl.homeaway.com/mda01/337b3cbe-80cf-400a-aece-c932852eb929.1.10";
string FinalTargetPath=@"F:\ReducedImage.png";
HttpWebRequest imageRequest = (HttpWebRequest)WebRequest.Create(ImageLink);
WebResponse imageResponse = imageRequest.GetResponse();
Stream responseStream = imageResponse.GetResponseStream();
string ImagePath= ReduceImageSize(0.5, responseStream, FinalTargetPath);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.