压缩图片或pdf

{
/// <summary>
/// 压缩图片或pdf大小的Level
/// </summary>
public enum ReduceSizeLevel
{
Small, //文件(小)
Middle, //文件 (中)
Large, //文件 (大)
None //不压缩
} public static class ReduceSizeHelper
{ #region 变量 /// <summary>
/// 图片的大小
/// </summary>
private static int[] Pix = new int[] { , , }; /// <summary>
/// 图片最小要求
/// </summary>
private static int[] PixMin = new int[] { , , }; /// <summary>
/// 图片的质量
/// </summary>
private static int[] PicQuantity = new int[] { , , }; /// <summary>
/// 调整后的文件大小
/// </summary>
private static int[] NewFileSize = new int[] { , , }; #endregion #region 公共方法 /// <summary>
/// 压缩图片大小
/// </summary>
/// <param name="info"></param>
/// <param name="ext"></param>
public static void ReduceImageSize(VMCustLoanDocInfo info, string ext, ReduceSizeLevel level)
{
if (level == ReduceSizeLevel.None) return;
int maxPix = ; //压缩后的尺寸
int minPix = ; //最小尺寸
int quantity = ; //质量百分比
int maxFileSize = ; //压缩后的文件大小
switch (level)
{
case ReduceSizeLevel.Small:
maxPix = Pix[];
minPix = PixMin[];
quantity = PicQuantity[];
maxFileSize = NewFileSize[];
break;
case ReduceSizeLevel.Middle:
maxPix = Pix[];
minPix = PixMin[];
quantity = PicQuantity[];
maxFileSize = NewFileSize[];
break;
case ReduceSizeLevel.Large:
maxPix = Pix[];
minPix = PixMin[];
quantity = PicQuantity[];
maxFileSize = NewFileSize[];
break;
default:
break;
}
FileInfo fileInfo = new FileInfo(info.DocName);
if (fileInfo.Length <= maxFileSize) return; IList<string> tmpFileNames = new List<string>(); //临时文件
using (System.Drawing.Image img = ImageHelper.ResizeImage(System.Drawing.Image.FromFile(info.DocName), maxPix, maxPix))
{
info.TmpFileName = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache).TrimEnd('\\') + "\\" + Util.GetGuid() + ext;
img.Save(info.TmpFileName);
tmpFileNames.Add(info.TmpFileName);
}
string tmpFileName = info.TmpFileName;
info.TmpFileName = reduceLoop(maxPix, minPix, quantity, maxFileSize, ref tmpFileNames, tmpFileName, ext); //删除临时文件
foreach (string fileName in tmpFileNames)
{
if (fileName == info.TmpFileName) continue;
try
{
File.Delete(fileName);
}
catch { }
}
} /// <summary>
/// 调整pdf里图片的大小
/// </summary>
/// <param name="info"></param>
/// <param name="level"></param>
public static void ReducePDFSize(VMCustLoanDocInfo info, ReduceSizeLevel level)
{
if (level == ReduceSizeLevel.None) return;
int maxPix = ; //压缩后的尺寸
int minPix = ; //最小尺寸
int quantity = ; //质量百分比
int maxFileSize = ; //压缩后的文件大小
switch (level)
{
case ReduceSizeLevel.Small:
maxPix = Pix[];
minPix = PixMin[];
quantity = PicQuantity[];
maxFileSize = NewFileSize[];
break;
case ReduceSizeLevel.Middle:
maxPix = Pix[];
minPix = PixMin[];
quantity = PicQuantity[];
maxFileSize = NewFileSize[];
break;
case ReduceSizeLevel.Large:
maxPix = Pix[];
minPix = PixMin[];
quantity = PicQuantity[];
maxFileSize = NewFileSize[];
break;
default:
break;
}
FileInfo fileInfo = new FileInfo(info.DocName);
if (fileInfo.Length <= maxFileSize) return; IList<string> tmpFileNames = new List<string>(); //临时文件 string imgExt = ".jpg"; using (Aspose.Pdf.Document document = new Aspose.Pdf.Document(info.DocName))
{
if (fileInfo.Length <= maxFileSize * document.Pages.Count) return;
foreach (Aspose.Pdf.Page page in document.Pages)
{
int idx = ;
foreach (Aspose.Pdf.XImage image in page.Resources.Images)
{
using (var imageStream = new MemoryStream())
{
// To compress images change the image type and resolution
image.Save(imageStream);
imageStream.Seek(, SeekOrigin.Begin);
//// Control image quality for better compression string tmpFileName = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache).TrimEnd('\\') + "\\" + Util.GetGuid() + imgExt;
tmpFileNames.Add(tmpFileName);
using (System.Drawing.Image img = System.Drawing.Image.FromStream(imageStream))
{
JXJR.CMS.Utility.ImageHelper.SaveJpeg(tmpFileName, img, );
}
tmpFileName = reduceLoop(maxPix, minPix, quantity, maxFileSize, ref tmpFileNames, tmpFileName, imgExt);
tmpFileNames.Add(tmpFileName); using (FileStream newStream = new FileStream(tmpFileName, FileMode.Open))
{
page.Resources.Images.Replace(idx, newStream);
}
} idx = idx + ;
}
} document.OptimizeResources();
// save the updated file
info.TmpFileName = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache).TrimEnd('\\') + "\\" + Util.GetGuid() + ".pdf";
document.Save(info.TmpFileName);
fileInfo = new FileInfo(info.DocName);
long size1 = fileInfo.Length;
fileInfo = new FileInfo(info.TmpFileName);
long size2 = fileInfo.Length;
if (size2 > size1)
{
info.TmpFileName = info.DocName;
}
}
} /// <summary>
/// 把一个pdf分割成多个pdf
/// </summary>
/// <param name="pdfFileName">原始pdf文件名</param>
/// <param name="newFileNamePrex">新pdf文件名的前面部分(后面部分是页码)</param>
/// <param name="oneFilePageCount">分割后每个pdf文件包含的页数</param>
/// <returns></returns>
public static List<string> SplitPDFBarCode(string pdfFileName, string newFileNamePrex, int oneFilePageCount)
{
bool includeFirstPage = false;
//分割后的存放路径
List<string> tmpFileNames = new List<string>();
if (!pdfFileName.ToLower().EndsWith(".pdf")) return tmpFileNames; using (Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(pdfFileName))
{
FileInfo fileInfo = new FileInfo(pdfFileName);
if (!fileInfo.Exists) return tmpFileNames;
newFileNamePrex = fileInfo.DirectoryName.EndsWith(@"\") ? fileInfo.DirectoryName + newFileNamePrex : fileInfo.DirectoryName + @"\" + newFileNamePrex; int i = includeFirstPage ? : ; //includeFirstPage是false时 不含首页(可能是条形码页面)
while (i <= pdfDocument.Pages.Count)
{
int pageCount = ;
using (Aspose.Pdf.Document newDocument = new Aspose.Pdf.Document())
{
int iFrom = i;
while (i <= pdfDocument.Pages.Count && pageCount <= oneFilePageCount)
{
Aspose.Pdf.Page pdfPage = pdfDocument.Pages[i];
newDocument.Pages.Add(pdfPage);
pageCount++;
i++;
}
string newFileName = newFileNamePrex;
if (pdfDocument.Pages.Count <= oneFilePageCount)
{
//不需要用页码标识
newFileName = newFileName + ".pdf";
}
else
{
if (includeFirstPage)
{
newFileName = oneFilePageCount > ? newFileName + "_" + iFrom + "-" + (i - ) + ".pdf" : newFileName + "_" + (i - ) + ".pdf";
}
else
{
newFileName = oneFilePageCount > ? newFileName + "_" + (iFrom - ) + "-" + (i - ) + ".pdf" : newFileName + "_" + (i - ) + ".pdf";
}
}
if (File.Exists(newFileName))
{
try
{
File.Delete(newFileName);
}
catch
{
MyMessageBox.Warning("无法删除" + newFileName + ",文件可能已经被打开,请先关闭该文件");
return new List<string>();
}
}
newDocument.Save(newFileName);
tmpFileNames.Add(newFileName);
}
}
return tmpFileNames;
}//using
} /// <summary>
/// 把一个pdf分割成多个pdf
/// </summary>
/// <param name="pdfFileName">原始pdf文件名</param>
/// <param name="oneFilePageCount">分割后每个pdf文件包含的页数</param>
/// <returns></returns>
public static List<string> SplitPDF(string pdfFileName, int oneFilePageCount)
{
bool includeFirstPage = true; //分割后的存放路径
List<string> tmpFileNames = new List<string>();
if (!pdfFileName.ToLower().EndsWith(".pdf")) return tmpFileNames; using (Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(pdfFileName))
{
if (pdfDocument.Pages.Count <= oneFilePageCount)
{
tmpFileNames.Add(pdfFileName);
return tmpFileNames;
}
FileInfo fileInfo = new FileInfo(pdfFileName);
if (!fileInfo.Exists) return tmpFileNames; string newFileNamePrex = ""; //新pdf文件名的前面部分(后面部分是页码)
newFileNamePrex = fileInfo.Name.Substring(, fileInfo.Name.Length - fileInfo.Extension.Length);
newFileNamePrex = fileInfo.DirectoryName.EndsWith(@"\") ? fileInfo.DirectoryName + newFileNamePrex : fileInfo.DirectoryName + @"\" + newFileNamePrex; int i = includeFirstPage ? : ; //includeFirstPage是false时 不含首页(可能是条形码页面)
while (i <= pdfDocument.Pages.Count)
{
int pageCount = ;
using (Aspose.Pdf.Document newDocument = new Aspose.Pdf.Document())
{
int iFrom = i;
while (i <= pdfDocument.Pages.Count && pageCount <= oneFilePageCount)
{
Aspose.Pdf.Page pdfPage = pdfDocument.Pages[i];
newDocument.Pages.Add(pdfPage);
pageCount++;
i++;
}
string newFileName = newFileNamePrex;
if (includeFirstPage)
{
newFileName = oneFilePageCount > ? newFileName + "_" + iFrom + "-" + (i - ) + ".pdf" : newFileName + "_" + (i - ) + ".pdf";
}
else
{
newFileName = oneFilePageCount > ? newFileName + "_" + (iFrom - ) + "-" + (i - ) + ".pdf" : newFileName + "_" + (i - ) + ".pdf";
}
if (File.Exists(newFileName))
{
try
{
File.Delete(newFileName);
}
catch
{
MyMessageBox.Warning("无法删除" + newFileName + ",文件可能已经被打开,请先关闭该文件");
return new List<string>();
}
}
newDocument.Save(newFileName);
tmpFileNames.Add(newFileName);
}
}
return tmpFileNames;
}//using
} #endregion #region 私有方法 /// <summary>
/// 循环调整图片直到满足要求
/// </summary>
/// <param name="maxPix">最大分辨率</param>
/// <param name="minPix">最小分辨率</param>
/// <param name="quantity">图片质量百分比</param>
/// <param name="maxFileSize">最大文件大小</param>
/// <param name="tmpFileNames">调整过程中产生的临时文件</param>
/// <param name="tmpFileName">初始文件名</param>
/// <param name="ext">文件后缀名</param>
/// <returns></returns>
private static string reduceLoop(int maxPix, int minPix, int quantity, int maxFileSize, ref IList<string> tmpFileNames, string tmpFileName, string ext)
{
FileInfo fileInfo = new FileInfo(tmpFileName);
while (fileInfo.Length > maxFileSize) //循环,直到满足要求
{
if ((int)(maxPix * 0.9) > minPix) maxPix = (int)(maxPix * 0.9); //继续调整大小 using (System.Drawing.Image img2 = ImageHelper.ResizeImage(System.Drawing.Image.FromFile(tmpFileName), maxPix, maxPix))
{
tmpFileName = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache).TrimEnd('\\') + "\\" + Util.GetGuid() + ext;
img2.Save(tmpFileName);
tmpFileNames.Add(tmpFileName);
fileInfo = new FileInfo(tmpFileName);
if (fileInfo.Length > maxFileSize)
{
tmpFileName = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache).TrimEnd('\\') + "\\" + Util.GetGuid() + ext;
ImageHelper.SaveJpeg(tmpFileName, img2, quantity);
tmpFileNames.Add(tmpFileName);
fileInfo = new FileInfo(tmpFileName);
quantity -= ; //再降低质量
}
}//using img2
}//while
return tmpFileName;
} ///// <summary>
///// 复制pdf文件
///// </summary>
///// <param name="docName"></param>
///// <param name="newFileNamePrex">pdf文件名(不含".pdf")</param>
///// <returns></returns>
//public static string CopyPDF(string docName, string newFileNamePrex)
//{
// FileInfo fileInfo = new FileInfo(docName);
// newFileNamePrex = fileInfo.DirectoryName.EndsWith(@"\") ? fileInfo.DirectoryName + newFileNamePrex : fileInfo.DirectoryName + @"\" + newFileNamePrex;
// newFileNamePrex += ".pdf";
// File.Copy(docName, newFileNamePrex, true);
// return newFileNamePrex;
//} #endregion }
}

压缩图片或pdf的更多相关文章

  1. java (图片转PDF)

    1.导入jar包 itextpdf-5.5.12.jar 2.写代码 package com.util; import java.io.File; import java.io.FileNotFoun ...

  2. iOS学习-压缩图片(改变图片的宽高)

    压缩图片,图片的大小与我们期望的宽高不一致时,我们可以将其处理为我们想要的宽高. 传入想要修改的图片,以及新的尺寸 -(UIImage*)imageWithImage:(UIImage*)image ...

  3. Android压缩图片到100K以下并保持不失真的高效方法

    前言:目前一般手机的相机都能达到800万像素,像我的Galaxy Nexus才500万像素,拍摄的照片也有1.5M左右.这么大的照片上传到服务器,不仅浪费流量,同时还浪费时间. 在开发Android企 ...

  4. Android 高清加载巨图方案 拒绝压缩图片

    Android 高清加载巨图方案 拒绝压缩图片 转载请标明出处: http://blog.csdn.net/lmj623565791/article/details/49300989: 本文出自:[张 ...

  5. js压缩图片base64长度

    var myCanvas=$('.img-container > img').cropper('getCroppedCanvas'); (function (base64){ var image ...

  6. js上传压缩图片

    原文链接:http://blog.csdn.net/iefreer/article/details/53039848 手机用户拍的照片通常会有2M以上,这对服务器带宽产生较大压力. 因此在某些应用下( ...

  7. 等比例压缩图片到指定的KB大小

    基本原理: 取原来的图片,长宽乘以比例,重新生成一张图片,获取这张图片的大小,如果还是超过预期大小,继续在此基础上乘以压缩比例,生成图片,直到达到预期 /** * @获取远程图片的体积大小 单位byt ...

  8. 移动端使用localResizeIMG4压缩图片

    移动h5开发避免不了上传图片,一般我们使用html自带的控件input或者使用微信上传API.但微信上传API不是任何地方都可以使用的,使用html自带的控件input上传又免不了图片体积太大,上传不 ...

  9. java 上传图片 并压缩图片大小

    Thumbnailator 是一个优秀的图片处理的Google开源Java类库.处理效果远比Java API的好.从API提供现有的图像文件和图像对象的类中简化了处理过程,两三行代码就能够从现有图片生 ...

随机推荐

  1. [bzoj3714] [PA2014] Kuglarz(最小生成树)

    我们考虑这个题...思路比较神仙. 就是我们设\(sum[i]\)为前i个的区间里的情况,然后我们知道\(sum[j]\)的话,我们就可以知道\(j-i\)的情况了 所以说这很像最小生成树里面的约束条 ...

  2. OCP 12c最新考试题库及答案(071-2)

    2019-02-12 16:23:54   2.(4-7) choose the best answer:You need to display the first names of all cust ...

  3. 如何构建debian包

        1)安装dh_make如下: sudo apt-get intasll aptitude sudo aptitude install dh_make    2)以jsoncpp为例,说明如何生 ...

  4. Win8.1下安装sql server 2008 r2详解

    我是来斗图的,安装了好多次,有一些配置还是不能烂熟于心啊,所以就想起来了米老师那句话,学习是个反复的过程.写个教程吧,很简单但是很实用. 首先打开"setup.exe"出现以下界面 ...

  5. CentOS安装搭建zookeeper

    原文连接:https://www.cnblogs.com/rwxwsblog/p/5806075.html zookeeper集群搭建(三台) 注意关闭机器防火墙! 配置ip别名:编辑文件  # /e ...

  6. POJ1591 M*A*S*H (JAVA)

    这水题,真的坑 测试数据最后有空行,如果用sc.hasNextLine()判断,会RE 要改为sc.hasNext() 搞了我一上午,烦死 import java.util.*; public cla ...

  7. 2016级算法第二次上机-D.Bamboo的饼干

    Bamboo的饼干 分析 从两个数组中各取一个数,使两者相加等于给定值.要注意去重和排序 难度不大,方法很多,基本只要不大于O(n^2 ) 的都可以过.本意想考察二分搜索 还可以借助stl中的map, ...

  8. Linux-Web应用服务性能测试初探

    一.服务端与客户端的准备工作 对于服务器最想要的数据就是,每秒支持的并发数,以及相应的内存CPU使用情况. 服务端需要设置最大打开描述符的限制(以支持创建大量的socket),配置socket参数.客 ...

  9. Maven web项目(简单的表单提交) 搭建(eclipse)

    我们将会搭建一个,基于Maven管理的,具有简单的表单提交功能的web项目,使用DAO--service--WEB三层结构,服务器使用Tomcat 1 项目基本结构的搭建 左上角File---> ...

  10. wifi测距

    #include "ESP8266WiFi.h" #include "math.h" //d = 10^(A-(abs(rssi)) / (10 * n)) 信 ...