I have a problem when I put an image as Stream to a Bitmap.
The code swaps the width and height of the image.
The real dimensions of the image are:
Real width: 3216px
Real height: 4288px
But the code below swaps it so Height is 3216px and Width: 4288px
What happens is that the image also gets rotated when I save the bitmap.
FileStream fs = new FileStream("C:/image.jpg", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
Bitmap bitmap = new Bitmap(fs);
int width = bitmap.Width;
int height = bitmap.Height;
bool hasresized = false;
double ratio = Convert.ToDouble(width) / Convert.ToDouble(height);
while (true) {
if (width <= 900 && height <= 675) {
break;
}
height--;
width = Convert.ToInt32(ratio * Convert.ToDouble(height));
}
if (width != bitmap.Width || height != bitmap.Height) {
//We need to resize
bitmap = ResizeImage(bitmap, width, height);
hasresized = true;
}
SaveImage(bitmap, "C:/test.jpg", ImageFormat.Jpeg, quality);
fs.Close();
public void SaveImage(Bitmap bitmap, String fileName, ImageFormat imageFormat, long quality = 100 L) {
using(var encoderParameters = new EncoderParameters(1))
using(encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality)) {
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
bitmap.Save(fileName, codecs.Single(codec => codec.FormatID == imageFormat.Guid), encoderParameters);
}
}
public Bitmap ResizeImage(Image image, int width, int height) {
var destRect = new Rectangle(0, 0, width, height);
var destImage = new Bitmap(width, height);
destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
using(var graphics = Graphics.FromImage(destImage)) {
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);
}
return destImage;
}
This is the image when it is saved. It has rotated 90 to the right: