using System;
using System.Drawing;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace 图片压缩
{
public class Program
{
static void Main(string[] args)
{
DirectoryInfo root = new DirectoryInfo(@"D:\桌面\测试");
foreach (FileInfo f in root.GetFiles())
{
GetImage(f.FullName,f.Name);
Console.WriteLine(f.Name);
}
Console.WriteLine("Hello World!");
}
public static void GetImage(string path,string name)
{
var imageStr = ImageToBase64(path);
var newImageStr = GetImg(imageStr, 1);
using (var stream = new FileStream($@"D:\桌面\测试新\tu{name}", FileMode.Create))
{
var match = Regex.Match(newImageStr, "data:image/png;base64,([\\w\\W]*)$");
if (match.Success)
{
newImageStr = match.Groups[1].Value;
}
var imgByte = Convert.FromBase64String(newImageStr);
stream.Write(imgByte, 0, imgByte.Length);
stream.Flush();
}
}
///
/// Image 转成 base64
///
///
public static string ImageToBase64(string filePath)
{
Bitmap bmp = new Bitmap(filePath);
MemoryStream ms = new MemoryStream();
bmp.Save(ms, bmp.RawFormat);
byte[] arr = new byte[ms.Length];
ms.Position = 0;
ms.Read(arr, 0, (int)ms.Length);
ms.Close();
return Convert.ToBase64String(arr);
}
///
/// 图片压缩
///
/// 图片base64
/// 图片类型,默认宽高
/// 图片最大限制
///
public static string GetImg(string imgstr,int type, int length = 1024 * 1536)
{
//1.5MB以内的图片,不做压缩处理
if (imgstr.Length < length)
return imgstr;
int width = 800, height = 560;
if (type == 1)
{
width = 1230;
height = 870;
}
byte[] imgBytes = Convert.FromBase64String(imgstr);
var stream = new MemoryStream(imgBytes);
var image = Image.FromStream(stream);
double newWidth, newHeight;
if (image.Width > image.Height)
{
newWidth = width;
newHeight = image.Height * (newWidth / image.Width);
}
else
{
newHeight = height;
newWidth = (newHeight / image.Height) * image.Width;
}
if (newWidth > width)
{
newWidth = width;
}
if (newHeight > height)
{
newHeight = height;
newWidth = image.Width * (newHeight / image.Height);
}
var outStream = new MemoryStream();
ImgThumbnail.Thumbnail(stream, outStream,Convert.ToInt32(newWidth),Convert.ToInt32(newHeight), 100, ImgThumbnail.ImgThumbnailType.WH);
var newImageStr = Convert.ToBase64String(outStream.ToArray());
while (newImageStr.Length>= length)
{
newImageStr= GetImg(newImageStr, type,length);
}
return newImageStr;
}
}
}
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Net.Mime;
using System.Text;
namespace 图片压缩
{
public class ImgThumbnail
{
#region 枚举
///
/// 指定缩放类型
///
public enum ImgThumbnailType
{
///
/// 无
///
Nothing = 0,
///
/// 指定高宽缩放(可能变形)
///
WH = 1,
///
/// 指定宽,高按比例
///
W = 2,
///
/// 指定高,宽按比例
///
H = 3,
///
/// 指定高宽裁减(不变形)
///
Cut = 4,
///
/// 按照宽度成比例缩放后,按照指定的高度进行裁剪
///
W_HCut = 5,
///
/// 长边优先
///
W_L = 5,
///
/// 短边优先
///
W_S = 5,
}
public enum ImgResize
{
///
/// 无
///
Nothing = 0,
///
/// 按长边优先
///
M_lfit = 1,
///
/// 按短边优先
///
M_mfit = 2,
}
#endregion
#region 图片压缩
///
/// 无损压缩图片
///
/// 原图片
/// 高度
///
/// 压缩质量 1-100
/// 压缩缩放类型
///
///
private static Bitmap Thumbnail(Stream sourceStream, int width, int height, int quality
, ImgThumbnailType type, out ImageFormat tFormat)
{
using (Image iSource = Image.FromStream(sourceStream))
{
tFormat = iSource.RawFormat;
//缩放后的宽度和高度
int toWidth = width;
int toHeight = height;
//
int x = 0;
int y = 0;
int oWidth = iSource.Width;
int oHeight = iSource.Height;
if (type == ImgThumbnailType.W_L) type = oWidth > oHeight ? ImgThumbnailType.W : ImgThumbnailType.H;
if (type == ImgThumbnailType.W_S) type = oWidth > oHeight ? ImgThumbnailType.H : ImgThumbnailType.W;
switch (type)
{
case ImgThumbnailType.WH://指定高宽缩放(可能变形)
{
break;
}
case ImgThumbnailType.W://指定宽,高按比例
{
toHeight = iSource.Height * width / iSource.Width;
break;
}
case ImgThumbnailType.H://指定高,宽按比例
{
toWidth = iSource.Width * height / iSource.Height;
break;
}
case ImgThumbnailType.Cut://指定高宽裁减(不变形)
{
if (iSource.Width / (double)iSource.Height > toWidth / (double)toHeight)
{
oHeight = iSource.Height;
oWidth = iSource.Height * toWidth / toHeight;
y = 0;
x = (iSource.Width - oWidth) / 2;
}
else
{
oWidth = iSource.Width;
oHeight = iSource.Width * height / toWidth;
x = 0;
y = (iSource.Height - oHeight) / 2;
}
break;
}
case ImgThumbnailType.W_HCut://按照宽度成比例缩放后,按照指定的高度进行裁剪
{
toHeight = iSource.Height * width / iSource.Width;
if (height < toHeight)
{
oHeight = oHeight * height / toHeight;
toHeight = toHeight * height / toHeight;
}
break;
}
default:
break;
}
Bitmap ob = new Bitmap(toWidth, toHeight);
//ImgWaterMark iwm = new ImgWaterMark();
//iwm.AddWaterMark(ob, towidth, toheight, "www.***.com");
Graphics g = Graphics.FromImage(ob);
g.Clear(Color.WhiteSmoke);
g.CompositingQuality = CompositingQuality.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(iSource
, new Rectangle(x, y, toWidth, toHeight)
, new Rectangle(0, 0, oWidth, oHeight)
, GraphicsUnit.Pixel);
g.Dispose();
return ob;
}
}
///
/// 无损压缩图片
///
/// 原图片文件流
/// 压缩后保存到流中
/// 高度
///
/// 压缩质量 1-100
/// 压缩缩放类型
///
public static bool Thumbnail(Stream sourceStream, Stream outStream, int width, int height, int quality, ImgThumbnailType type)
{
ImageFormat tFormat;
Bitmap ob = Thumbnail(sourceStream, width, height, quality, type, out tFormat);
//水印
//ImgWaterMark.AddWaterMark(ob, "www.***.com");
//以下代码为保存图片时,设置压缩质量
EncoderParameters ep = new EncoderParameters();
long[] qy = new long[1] { quality };//设置压缩的比例1-100
EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
ep.Param[0] = eParam;
try
{
ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo jpegICIinfo = null;
for (int i = 0; i < arrayICI.Length; i++)
{
if (arrayICI[i].FormatDescription.Equals("JPEG"))
{
jpegICIinfo = arrayICI[i];
break;
}
}
if (jpegICIinfo != null)
{
ob.Save(outStream, jpegICIinfo, ep);//jpegICIinfo是压缩后的新路径
}
else
{
ob.Save(outStream, tFormat);
}
return true;
}
catch
{
return false;
}
finally
{
//iSource.Dispose();
ob.Dispose();
}
}
///
/// 无损压缩图片
///
/// 原图片
/// 压缩后保存位置
/// 高度
///
/// 压缩质量 1-100
/// 压缩缩放类型
///
public static bool Thumbnail(string sourceFile, string targetFile, int width, int height, int quality, ImgThumbnailType type)
{
ImageFormat tFormat = null;
var fileBytes = File.ReadAllBytes(sourceFile);
var sourceStream = new MemoryStream(fileBytes);
Bitmap ob = Thumbnail(sourceStream, width, height, quality, type, out tFormat);
//以下代码为保存图片时,设置压缩质量
EncoderParameters ep = new EncoderParameters();
long[] qy = new long[1] { quality };//设置压缩的比例1-100
EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
ep.Param[0] = eParam;
try
{
ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo jpegICIinfo = null;
for (int i = 0; i < arrayICI.Length; i++)
{
if (arrayICI[i].FormatDescription.Equals("JPEG"))
{
jpegICIinfo = arrayICI[i];
break;
}
}
if (jpegICIinfo != null)
{
ob.Save(targetFile, jpegICIinfo, ep);//jpegICIinfo是压缩后的新路径
}
else
{
ob.Save(targetFile, tFormat);
}
return true;
}
catch
{
return false;
}
finally
{
//iSource.Dispose();
ob.Dispose();
}
}
#endregion
#region 生成缩略图
///
/// 生成缩略图
///
/// 原始图片文件
/// 质量压缩比
///
///
/// 输出文件名
/// 成功返回true,失败则返回false
public static bool GetThumImage(string sourceFile, long quality, int w, int h, string outputFile)
{
try
{
long imageQuality = quality;
Bitmap sourceImage = new Bitmap(sourceFile);
ImageCodecInfo myImageCodecInfo = GetEncoder(ImageFormat.Jpeg);
System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
EncoderParameters myEncoderParameters = new EncoderParameters(1);
EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, imageQuality);
myEncoderParameters.Param[0] = myEncoderParameter;
sourceImage.Save(outputFile, myImageCodecInfo, myEncoderParameters);
float xWidth = sourceImage.Width;
float yWidth = sourceImage.Height;
Bitmap newImage = new Bitmap(w, h);
Graphics g = Graphics.FromImage(newImage);
g.DrawImage(sourceImage, 0, 0, w, h);
g.Dispose();
newImage.Save(outputFile, myImageCodecInfo, myEncoderParameters);
return true;
}
catch
{
return false;
}
}
private static ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
#endregion
public static ImgThumbnailType GetThumbnailType(string w, string h, string t, string sourceFile)
{
//参数只有一个
if (w == "0" || h == "0")
{
return w == "0" ? ImgThumbnailType.H : ImgThumbnailType.W;
}
else
{
return t == "0" ? ImgThumbnailType.W_L : ImgThumbnailType.W_S;
}
}
///
/// 比较原图的高宽大小
///
/// 宽度
/// 高度
///
///
public static int GetImgResize(int w, int h, int t)
{
if (w > h) return t == 0 ? w : h;
return t == 0 ? h : w;
}
}
}