I spent the last 10-12 hours trying to figure out how to properly make the downloaded web image smaller in size and pixels in C # in the developed Windows Store application.
No matter what I do, I continue to receive artifacts on the final images, such as “half the image”, gray / dotted areas and the like. For example, if the stream was not cleaned correctly, although I believe that I did it (I did not do this in the code below, since it works without it ...)
This is my approach for image extraction - this part works, but is included here to make sure all the information is here (see code below):
- Get image url
- Use HttpWebRequest to get a response
- Create a stream to receive a response stream
- Create an empty StorageFile and open for writing
- Copy the response stream to the repository file.
- Close all
From there I need to do the following:
- Determine the size (e.g. using BitmapDecoder)
- If the image width exceeds a certain size (for example, 700 pixels), it must be changed.
- Regardless of the fact that files are always too large and need to be compressed even more
- The image must be saved as jpg with image quality set to medium / half-high setting
I have tried many things, including multi-threaded work with BitmapEncoder / BitmapDecoder, but no matter what, I still get semi-processed images.
Can someone help me find the right way to compress and resize images?
My code in current state:
using (var response = await HttpWebRequest.CreateHttp(internetUri).GetResponseAsync())
{
using (var stream = response.GetResponseStream())
{
var imageFolder = await localFolder.CreateFolderAsync(
CachedImagesFolderEndFolderPath, CreationCollisionOption.OpenIfExists);
string fileName = string.Format("{0}.jpg",
Path.GetFileNameWithoutExtension(Path.GetRandomFileName()));
var file = await imageFolder.CreateFileAsync(fileName,
CreationCollisionOption.ReplaceExisting);
using (var filestream = await file.OpenStreamForWriteAsync())
{
await stream.CopyToAsync(filestream);
}
}
}