using System; using System.Drawing; using System.IO; using System.Drawing.Imaging; using System.Drawing.Drawing2D; namespace Ants.Tools { public class Image { public int Width { get; set; } public int Height { get; set; } private Image() { } public Image(int width, int height) { this.Width = width; this.Height = height; } public MemoryStream getHightThumb(Stream imgData, string Mode_HW_W_H_Cut) { MemoryStream result = new MemoryStream(); System.Drawing.Image.GetThumbnailImageAbort myCallBack = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallBack); try { System.Drawing.Image originalImage = System.Drawing.Image.FromStream(imgData); int X, Y; X = Width; Y = Height; int towidth = X; int toheight = Y; int x = 0; int y = 0; int ow = originalImage.Width; int oh = originalImage.Height; switch (Mode_HW_W_H_Cut) { case "HW": //指定高寬縮放(可能變形) break; case "W"://指定寬,高按比例 toheight = originalImage.Height * X / originalImage.Width; break; case "H//指定高,寬按比例 towidth = originalImage.Width * Y / originalImage.Height; break; case "Cut": if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight) { oh = originalImage.Height; ow = originalImage.Height * towidth / toheight; y = 0; x = (originalImage.Width - ow) / 2; } else { ow = originalImage.Width; oh = originalImage.Width * Y / towidth; x = 0; y = (originalImage.Height - oh) / 2; } break; default: break; } System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight); System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.Clear(System.Drawing.Color.Transparent); g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel); bitmap.Save(result, System.Drawing.Imaging.ImageFormat.Jpeg); } catch { //do something } return result; } } } |