[HttpPost]
[AuthorizeIgnore]
public ActionResult PhoneUpload()
{
try
{
var files = Request.Files;
if (files == null || files.Count == 0)
throw new Exception("请选择需要上传的图片");
var upFile = files[0];
var allowType = new string[] { "image/jpeg", "image/jpg", "image/png", "image/gif" };
if (!allowType.Contains(upFile.ContentType))
throw new Exception("请上传“.jpg/.png/.gif”格式的图片");
if (upFile.ContentLength > 1024 * 1024 * 20)
throw new Exception("图片大小不能超20M");
string ext = upFile.FileName.Substring(upFile.FileName.LastIndexOf('.'));
var guid = Guid.NewGuid();
string strpath = Path.Combine("UploadFiles", "imagebanklog", guid + ext);
string strpath_th = Path.Combine("UploadFiles", "imagebanklog", guid + "_th" + ext);
string path = Path.Combine(Server.MapPath("~/"), strpath);
string path_th = Path.Combine(Server.MapPath("~/"), strpath_th);
upFile.SaveAs(path);
GetThumImage(path, 90, 1024, path_th);
try
{
System.IO.File.Delete(path);
}
catch { }
return Json(new { id = 0, success = true, result = strpath_th }, "text/html");
}
catch (Exception ex)
{
return Json(new { id = 0, success = false, msg = ex.Message.ToString() }, "text/html");
}
}
/// <summary>
/// 生成缩略图
/// </summary>
/// <param name="sourceFile">原始图片文件</param>
/// <param name="quality">质量压缩比,0-100,100是最清晰</param>
/// <param name="width">最大宽度</param>
/// <param name="outputFile">输出文件名</param>
/// <returns>成功返回true,失败则返回false</returns>
private bool GetThumImage(string sourceFile, long quality, int width, string outputFile)
{
try
{
long imageQuality = quality;
Bitmap sourceImage = new Bitmap(sourceFile);
var oWidth = sourceImage.Width;
var oHeight = sourceImage.Height;
var height = oHeight;
if (width > oWidth)
{
width = oWidth;
}
else
{
height = width * oHeight / oWidth;
}
var myImageCodecInfo = GetEncoderInfo("image/jpeg");
var myEncoder = System.Drawing.Imaging.Encoder.Quality;
var myEncoderParameters = new EncoderParameters(1);
var myEncoderParameter = new EncoderParameter(myEncoder, imageQuality);
myEncoderParameters.Param[0] = myEncoderParameter;
float xWidth = sourceImage.Width;
float yWidth = sourceImage.Height;
Bitmap newImage = new Bitmap(width, height);
Graphics g = Graphics.FromImage(newImage);
g.DrawImage(sourceImage, 0, 0, width, height);
g.Dispose();
newImage.Save(outputFile, myImageCodecInfo, myEncoderParameters);
sourceImage.Dispose();
sourceImage = null;
newImage.Dispose();
newImage = null;
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 获取图片编码信息
/// </summary>
private static ImageCodecInfo GetEncoderInfo(String mimeType)
{
int j;
ImageCodecInfo[] encoders;
encoders = ImageCodecInfo.GetImageEncoders();
for (j = 0; j < encoders.Length; ++j)
{
if (encoders[j].MimeType == mimeType)
return encoders[j];
}
return null;
}