代码如下:
/// <summary>
/// 图片存储到本地文件夹
/// </summary>
/// <param name="defaultPath">默认的文件夹路径</param>
/// <param name="bytes"></param>
/// <param name="fileName">存储的文件名</param>
/// <param name="width">显示图片框的width</param>
/// <param name="height">显示图片框的height</param>
public bool ImageStroge(string defaultPath, byte[] bytes, string fileName, int width, int height)
{
var path = string.Format("{0}{1}", defaultPath, DateTime.Now.ToString("yyyyMM"));
//判断文件夹是否存在,不存在则自动创建该文件夹
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
var imagePath = string.Format(path + "\\{0}.jpg", fileName);
System.IO.File.WriteAllBytes(imagePath, bytes);
ScaledImageCreate(imagePath, width, height);
return true;
}
//图片缩略图
private bool ScaledImageCreate(string filePath, int width, int height)
{
string smallPath = System.IO.Path.GetDirectoryName(filePath) + "//small//";
if (!Directory.Exists(smallPath))
Directory.CreateDirectory(smallPath);
string file_path = filePath;
string new_file_path = System.IO.Path.GetDirectoryName(file_path) + "//small//" + System.IO.Path.GetFileName(filePath);
Image img = Image.FromFile(file_path);
string fileNameExtension = Path.GetExtension(file_path).ToLower();
ImageFormat imageType = GetImageType(fileNameExtension);
if (img == null)
{
return false;
}
int img_width = img.Width;
int img_height = img.Height;
if (img_width < 1 || img_height < 1)
{
return false;
}
float scale = Math.Min(width / (float)img_width, height / (float)img_height);
int new_width = (int)Math.Round(img_width * scale, 0);
int new_height = (int)Math.Round(img_height * scale, 0);
Bitmap new_image = new Bitmap(new_width, new_height);
Graphics g = Graphics.FromImage(new_image);
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
foreach (PropertyItem pItem in img.PropertyItems)
{
new_image.SetPropertyItem(pItem);
}
g.DrawImage(img, new Rectangle(0, 0, new_width, new_height));
img.Dispose();
new_image.Save(new_file_path, imageType);
new_image.Dispose();
return true;
}
private ImageFormat GetImageType(string fileExt)
{
switch (fileExt)
{
case ".jpg":
return ImageFormat.Jpeg;
case ".gif":
return ImageFormat.Gif;
default: // (png)
return ImageFormat.Png;
}
}