using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
namespace WinWorkManage
{
public class ImageHelper
{
public Color tBackground = Color.Transparent;
public Color tBorder = Color.Transparent;
public Color tShadow = Color.Transparent;
#region 属性
/// <summary>
/// 相框的宽度
/// </summary>
public int Width { get; set; }
/// <summary>
/// 相框的高度
/// </summary>
public int Height { get; set; }
/// <summary>
/// 待处理的图片的物理路径
/// </summary>
public string Path { get; set; }
#endregion
private bool ThumbnailCallBack()//GDI+委托
{
return false;
}
/// <summary>
/// 图片缩略图转换转换
/// </summary>
/// <param name="path">路径</param>
/// <param name="width">图片框宽度</param>
/// <param name="height">图片框高度</param>
/// <param name="Stream">Image数据流</param>
public static MemoryStream ConverSionImage(string path, int width, int height)
{
ImageHelper helper = new ImageHelper();
helper.Path = path;
helper.Width = width;
helper.Height = height;
bool ok = false;
System.IO.MemoryStream ms = helper.getThumb(out ok);
return ms;
}
/// <summary>
/// 缩略图片的函数
/// </summary>
/// <param name="OK">用来判断转换是否成功</param>
/// <returns>处理好的图片缩略图放入内存中</returns>
public MemoryStream getThumb(out bool OK)
{
OK = false;
int X, Y;
System.Drawing.Image myThumbnail = System.Drawing.Image.FromFile(Path);
try
{
Bitmap myBitmap = new Bitmap(Path);
X = myBitmap.Width;
Y = myBitmap.Height;
decimal a = (decimal)X / (decimal)Y;
decimal b = (decimal)Width / (decimal)Height;
System.Drawing.Image.GetThumbnailImageAbort myCallBack = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallBack);
int newWidth;
int newHeight;
if (Width * Height < X * Y)
{
if (b > a)
{
newHeight = Height;
newWidth = (int)decimal.Round(newHeight * a, 0, MidpointRounding.AwayFromZero);
}
else
{
newWidth = Width;
newHeight = (int)decimal.Round(Width / a, 0, MidpointRounding.AwayFromZero);
}
myThumbnail = myBitmap.GetThumbnailImage(newWidth, newHeight, myCallBack, IntPtr.Zero);//生成缩略图
}
else
{
myThumbnail = System.Drawing.Image.FromFile(Path);
}
OK = true;
myBitmap.Dispose();
}
catch
{
OK = false;
}
System.IO.MemoryStream ms = new System.IO.MemoryStream();
myThumbnail.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
return ms;
}
}
}