c# jpg图片压缩
public bool getThumImage(HttpContext context, string path, string imagname)
{
bool l_b = false;
HttpFileCollection HFC = context.Request.Files;
HttpPostedFile HF = HFC[0];
try
{
if (HF.ContentLength > 0)
{
if (!System.IO.Directory.Exists(path+"temp/"))
{
System.IO.Directory.CreateDirectory(path+"temp/");
}
//当文件类型为jpg并且带下超过3M进行压缩处理
if (System.IO.Path.GetExtension(HF.FileName).ToUpper() == ".JPG")
{
if (HF.ContentLength > 2 * 1024 * 1024)
{
HF.SaveAs(path + "temp/" + imagname);
ImageThumbnail imgnew = new ImageThumbnail(path + "temp/" + imagname);
l_b = imgnew.ReducedImage(0.6, path + imagname);
imgnew.dispose();
}
else
{
HF.SaveAs(path + imagname);
l_b = true;
}
}
else
{
HF.SaveAs(path + imagname);
l_b = true;
}
}
else
{
l_b = false;
}
return l_b;
}
catch (Exception ex)
{
return false;
}
}
using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
public class ImageThumbnail
{
public Image ResourceImage;
private int ImageWidth;
private int ImageHeight;
public string ErrorMessage;
public ImageThumbnail(string ImageFileName)
{
ResourceImage = Image.FromFile(ImageFileName);
ErrorMessage = "";
}
public bool ThumbnailCallback()
{
return false;
}
// 方法1,按大小
public bool ReducedImage(int Width, int Height, string targetFilePath)
{
try
{
Image ReducedImage;
Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback);
ReducedImage = ResourceImage.GetThumbnailImage(Width, Height, callb, IntPtr.Zero);
ReducedImage.Save(@targetFilePath, ImageFormat.Jpeg);
ReducedImage.Dispose();
return true;
}
catch (Exception e)
{
ErrorMessage = e.Message;
return false;
}
}
// 方法2,按百分比 缩小60% Percent为0.6 targetFilePath为目标路径
public bool ReducedImage(double Percent, string targetFilePath)
{
try
{
Image ReducedImage;
Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback);
ImageWidth = Convert.ToInt32(ResourceImage.Width * Percent);
ImageHeight = (ResourceImage.Height) * ImageWidth / ResourceImage.Width;//等比例缩放
//ReducedImage = ResourceImage.GetThumbnailImage(ImageWidth, ImageHeight, callb, IntPtr.Zero);
ReducedImage = new System.Drawing.Bitmap(ResourceImage, ImageWidth, ImageHeight);
ReducedImage.Save(@targetFilePath, ImageFormat.Jpeg);
ReducedImage.Dispose();
return true;
}
catch (Exception e)
{
ErrorMessage = e.Message;
return false;
}
}
public void dispose()
{
ResourceImage.Dispose();
}
}