C#将上传图片压缩(制作成缩略图)
1.制成缩略图方法
/// <summary>
/// 制作缩略图
/// </summary>
/// <param name="original">图片对象</param>
/// <param name="newFileName">新图路径</param>
/// <param name="maxWidth">最大宽度</param>
/// <param name="maxHeight">最大高度</param>
public static void ThumbImg(System.Drawing.Image original, string newFileName, int maxWidth, int maxHeight)
{
Size newSize = ResizeImage(original.Width, original.Height, maxWidth, maxHeight);
using (System.Drawing.Image displayImage = new Bitmap(original, newSize))
{
try
{
displayImage.Save(newFileName, original.RawFormat);
}
finally
{
original.Dispose();
}
}
}
2.进行压缩过程中,有时会丢失正确的位置信息,需旋转到正确的位置
/// <summary>
/// 将图片旋转到正确位置
/// </summary>
/// <param name="image"></param>
/// <returns></returns>
public static void OrientationImage(Image image)
{
if (Array.IndexOf(image.PropertyIdList, 274) > -1)
{
var orientation = (int)image.GetPropertyItem(274).Value[0];
switch (orientation)
{
case 1:
// No rotation required.
break;
case 2:
image.RotateFlip(RotateFlipType.RotateNoneFlipX);
break;
case 3:
image.RotateFlip(RotateFlipType.Rotate180FlipNone);
break;
case 4:
image.RotateFlip(RotateFlipType.Rotate180FlipX);
break;
case 5:
image.RotateFlip(RotateFlipType.Rotate90FlipX);
break;
case 6:
image.RotateFlip(RotateFlipType.Rotate90FlipNone);
break;
case 7:
image.RotateFlip(RotateFlipType.Rotate270FlipX);
break;
case 8:
image.RotateFlip(RotateFlipType.Rotate270FlipNone);
break;
}
image.RemovePropertyItem(274);
}
}
3.使用上述方法进行图片处理
public void getImg()
{
Image img = Image.FromStream(File.OpenReadStream()); //直接将文件转为文件流形式
OrientationImage(img);
ThumbImg(img, imgroute, 600, 800); // imgroute指图片存储路径 600 指宽度 800指高度
}

浙公网安备 33010602011771号