private void ReduceImageSize(double scaleFactor, Stream sourcePath, string targetPath)
{
const int OrientationKey = 0x112;
const int NotSpecified = 0;
const int NormalOrientation = 1;
const int MirrorHorizontal = 2;
const int UpsideDown = 3;
const int MirrorVertical = 4;
const int MirrorHorizontalAndRotateRight = 5;
const int RotateLeft = 6;
const int MirorHorizontalAndRotateLeft = 7;
const int RotateRight = 8;
using (var image = System.Drawing.Image.FromStream(sourcePath))
{
var newWidth = System.Convert.ToInt32((image.Width * scaleFactor));
var newHeight = System.Convert.ToInt32((image.Height * scaleFactor));
if (image.Height > 3000)
{
newHeight = System.Convert.ToInt32((image.Height * 0.25));
newWidth = System.Convert.ToInt32((image.Width * 0.25));
}
if (image.Height <= 600)
{
newHeight = System.Convert.ToInt32((image.Height * 1));
newWidth = System.Convert.ToInt32((image.Width * 1));
}
var thumbnailImg = new Bitmap(newWidth, newHeight);
var thumbGraph = Graphics.FromImage(thumbnailImg);
if (image.Height > 3000)
{
thumbGraph.CompositingQuality = CompositingQuality.HighSpeed;
thumbGraph.SmoothingMode = SmoothingMode.HighSpeed;
}
else if (image.Height <= 600)
{
thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
}
else
{
thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
}
thumbGraph.InterpolationMode = InterpolationMode.High;
var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
thumbGraph.DrawImage(image, imageRectangle);
if (image.PropertyIdList.Contains(OrientationKey))
{
var orientation = System.Convert.ToInt32(image.GetPropertyItem(OrientationKey).Value[0]);
switch (orientation)
{
case NotSpecified: // Assume it is good.
case NormalOrientation:
// No rotation required.
break;
case MirrorHorizontal:
thumbnailImg.RotateFlip(RotateFlipType.RotateNoneFlipX);
break;
case UpsideDown:
thumbnailImg.RotateFlip(RotateFlipType.Rotate180FlipNone);
break;
case MirrorVertical:
thumbnailImg.RotateFlip(RotateFlipType.Rotate180FlipX);
break;
case MirrorHorizontalAndRotateRight:
thumbnailImg.RotateFlip(RotateFlipType.Rotate90FlipX);
break;
case RotateLeft:
thumbnailImg.RotateFlip(RotateFlipType.Rotate90FlipNone);
break;
case MirorHorizontalAndRotateLeft:
thumbnailImg.RotateFlip(RotateFlipType.Rotate270FlipX);
break;
case RotateRight:
thumbnailImg.RotateFlip(RotateFlipType.Rotate270FlipNone);
break;
default:
throw new NotImplementedException("An orientation of " + orientation + " isn't implemented.");
}
}
thumbnailImg.Save(targetPath, image.RawFormat);
}
}
Yeah thank you...
ReplyDelete