I have a user gallery at the site and it is possible for visitors to upload some images. After upload image should be resized to some predefined presets. In addition original image should be saved too. All works fine for png
and bmp
image formats. But if I upload gif
format or jpeg
with a predominance of one color uploaded original image seems to be compressed.
For example:
Original:
Uploaded:
I thorougly searched in google and found some examples how to upload image right. At the end I have written the next method:
void UploadImagePreset(Image image, ImageFormat imgFormat, string imgPath)
{
using (var uploadStream = imageUploader.CreateUploadStream(imagePath))
{
var newWidth = image.Width;
var newHeight = image.Height;
using (var outBitmap = new Bitmap(newWidth, newHeight))
{
using (var outGraph = Graphics.FromImage(outBitmap))
{
outGraph.CompositingQuality = CompositingQuality.HighQuality;
outGraph.SmoothingMode = SmoothingMode.HighQuality;
outGraph.PixelOffsetMode = PixelOffsetMode.HighQuality;
outGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
var imageRect = new Rectangle(0, 0, newWidth, newHeight);
outGraph.DrawImage(image, imageRect);
outBitmap.Save(uploadStream, imgFormat);
}
}
}
}
But it did not help. Uploaded image was the same as described above. I have tryied to specify qaulity of the results image like this:
var encoderParameters = new EncoderParameters();
var encoderParameter = new EncoderParameter(Encoder.Quality, 100);
encoderParameters.Param[0] = encoderParameter;
var encoder = ImageCodecInfo.GetImageEncoders()
.Where(e => e.FormatID == imgFormat.Guid)
.FirstOrDefault();
outBitmap.Save(uploadStream, encoder, encoderParameters);
It does not work too. In addition when I upload jpeg image exception occurs.
Is any way to upload image without compressing or resizing? I have spent some hours trying solve this issue and stuck on it.