开门见山:在上一篇文章提取Office文件(Word、PPT)中的所有图片 中已经介绍了对特定格式(后缀为.docx
、.pptx
、.xlsx
)Office文件的解析。对于一个Office文件来说,想要减少文件占用的空间大小,最直接的方式就是降低内部引用的资源的大小。最简单的办法,直接对图片进行压缩就可以达到对整个Office文件瘦身的效果。
代码:获取PPT中所有引用到的图片文件,压缩后覆盖掉原文件
using DocumentFormat.OpenXml.Packaging;
/// <summary>
/// PPT文件压缩---压缩图片
/// </summary>
/// <param name="sourcePath">源文件路径</param>
/// <param name="targetDir">目标文件存放目录</param>
/// <returns></returns>
public static void CompressPPTImages(string sourcePath,string targetDir)
{
using (PresentationDocument presentationDocument = PresentationDocument.Open(filePath, isEditable: true))
{
PresentationPart presentationPart = presentationDocument.PresentationPart;
DocumentFormat.OpenXml.Presentation.Presentation presentation = presentationPart.Presentation;
List<ImagePart> list = new List<ImagePart>();
foreach (DocumentFormat.OpenXml.Presentation.SlideId item in presentation.SlideIdList.OfType<DocumentFormat.OpenXml.Presentation.SlideId>())
{
SlidePart slidePart = presentationPart.GetPartById(item.RelationshipId) as SlidePart;
list.AddRange(slidePart.ImageParts);
}
List<IGrouping<string, ImagePart>> list2 = list.GroupBy(d => d.Uri.OriginalString).ToList();
string sFile = Path.Combine( System.Environment.GetEnvironmentVariable("TEMP"), "sfile.tmp");
string dFile = Path.Combine( System.Environment.GetEnvironmentVariable("TEMP"), "dfile.tmp");
for (int i = 0; i < list2.Count; i++)
{
try
{
ImagePart imagePart = list2[i].First();
using (Stream stream = imagePart.GetStream(FileMode.Open))
{
using (Bitmap bitmap = new Bitmap(stream))
{
bitmap.Save(sFile);
}
}
if (CompressImage(sFile, dFile, 40))
{
using (FileStream sourceStream = new FileStream(dFile, FileMode.Open))
{
imagePart.FeedData(sourceStream);
}
}
}
catch (Exception ex)
{
LogHelper.Log(ex.Message);
}
}
presentation.Save();
File.Delete(sFile);
File.Delete(dFile);
}
}
图片无损压缩代码
/// <summary>
/// 无损压缩图片
/// </summary>
/// <param name="sFile">原图片地址</param>
/// <param name="dFile">压缩后保存图片地址</param>
/// <param name="flag">压缩质量(数字越小压缩率越高)1-100</param>
/// <param name="size">压缩后图片的最大大小</param>
/// <param name="sfsc">是否是第一次调用</param>
/// <returns></returns>
public static bool CompressImage(string sFile, string dFile, int flag = 90, int size = 300, bool sfsc = true)
{
//如果是第一次调用,原始图像的大小小于要压缩的大小,则直接复制文件,并且返回true
FileInfo firstFileInfo = new FileInfo(sFile);
if (sfsc == true && firstFileInfo.Length < size * 1024)
{
firstFileInfo.CopyTo(dFile);
return true;
}
//跳出死循环
if (sfsc == false && flag <= 0)
{
return true;
}
Image iSource = Image.FromFile(sFile);
ImageFormat tFormat = iSource.RawFormat;
int dHeight = iSource.Height / 2;
int dWidth = iSource.Width / 2;
Bitmap ob = new Bitmap(dWidth, dHeight);
using (Graphics g = Graphics.FromImage(ob))
{
g.Clear(Color.WhiteSmoke);
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(iSource, new Rectangle(0, 0, dWidth, dHeight), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
}
//以下代码为保存图片时,设置压缩质量
EncoderParameters ep = new EncoderParameters();
long[] qy = new long[1];
qy[0] = flag;//设置压缩的比例1-100
EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
ep.Param[0] = eParam;
try
{
ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo jpegICIinfo = arrayICI.ToList().FirstOrDefault(d => d.FormatDescription.Equals("JPEG"));
if (jpegICIinfo != null)
{
ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
FileInfo fi = new FileInfo(dFile);
if (fi.Length > 1024 * size)
{
flag = flag - 10;
CompressImage(sFile, dFile, flag, size, false);
}
}
else
{
ob.Save(dFile, tFormat);
}
return true;
}
catch
{
return false;
}
finally
{
iSource.Dispose();
ob.Dispose();
}
}