I have already read a lot of posts on Stack about image resizing and quality reducing, but non of them has been about reducing quality to certain physical disk space
I have a code that takes a picture:
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)
{
}
}
Now i need to send the data to the server, but before, i need to ensure that the photo is not more than 3 MB.
So i do this:
BasicProperties pro = await photo.GetBasicPropertiesAsync();
if (pro.Size < 3072)
{
// SEND THE FILE TO SERVER
}
else
{
// DECREASE QUALITY BEFORE SENDING
}
So the question is about ELSE block
Is there a better or maybe i have missed some built-in approach to fit image into the certain amount of megabytes by decreasing it's quality?
Because doing this:
while (pro.Size <= 3072)
{
photo = // some logic to decrease quality on 10%
}
Doesn't really look good.
Just Create one function :
/// <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 "";
}
}
And then call this function in your else block as below you will get same image with reduced size :
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.