压缩图片或pdf
压缩图片或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的更多相关文章
- java (图片转PDF)
1.导入jar包 itextpdf-5.5.12.jar 2.写代码 package com.util; import java.io.File; import java.io.FileNotFoun ...
- iOS学习-压缩图片(改变图片的宽高)
压缩图片,图片的大小与我们期望的宽高不一致时,我们可以将其处理为我们想要的宽高. 传入想要修改的图片,以及新的尺寸 -(UIImage*)imageWithImage:(UIImage*)image ...
- Android压缩图片到100K以下并保持不失真的高效方法
前言:目前一般手机的相机都能达到800万像素,像我的Galaxy Nexus才500万像素,拍摄的照片也有1.5M左右.这么大的照片上传到服务器,不仅浪费流量,同时还浪费时间. 在开发Android企 ...
- Android 高清加载巨图方案 拒绝压缩图片
Android 高清加载巨图方案 拒绝压缩图片 转载请标明出处: http://blog.csdn.net/lmj623565791/article/details/49300989: 本文出自:[张 ...
- js压缩图片base64长度
var myCanvas=$('.img-container > img').cropper('getCroppedCanvas'); (function (base64){ var image ...
- js上传压缩图片
原文链接:http://blog.csdn.net/iefreer/article/details/53039848 手机用户拍的照片通常会有2M以上,这对服务器带宽产生较大压力. 因此在某些应用下( ...
- 等比例压缩图片到指定的KB大小
基本原理: 取原来的图片,长宽乘以比例,重新生成一张图片,获取这张图片的大小,如果还是超过预期大小,继续在此基础上乘以压缩比例,生成图片,直到达到预期 /** * @获取远程图片的体积大小 单位byt ...
- 移动端使用localResizeIMG4压缩图片
移动h5开发避免不了上传图片,一般我们使用html自带的控件input或者使用微信上传API.但微信上传API不是任何地方都可以使用的,使用html自带的控件input上传又免不了图片体积太大,上传不 ...
- java 上传图片 并压缩图片大小
Thumbnailator 是一个优秀的图片处理的Google开源Java类库.处理效果远比Java API的好.从API提供现有的图像文件和图像对象的类中简化了处理过程,两三行代码就能够从现有图片生 ...
随机推荐
- GridControl中文属性
1 Appearance EmbeddedNavigator 嵌入导航器 (DataBindings) 数据绑定 (Advanced) 高级设置 Tag Text AccessibleDes ...
- 贝塞尔曲线 WPF MVVM N阶实现 公式详解+源代码下载
源代码下载 效果图: 本程序主要实现: N阶贝塞尔曲线(通用公式) 本程序主要使用技术 MVVM InterAction 事件绑定 动态添加Canvas的Item 第一部分公式: n=有效坐标点数量 ...
- leecode刷题(10)-- 旋转图像
leecode刷题(10)-- 旋转图像 旋转图像 描述: 给定一个 n × n 的二维矩阵表示一个图像. 将图像顺时针旋转 90 度. 说明: 你必须在原地旋转图像,这意味着你需要直接修改输入的二维 ...
- Java实现文件重命名
最近在做一个Android上面的一个文件管理器的apk,有文件名重命名和剪切的功能. 一般的思路如下: 重命名:先新建一个文件,复制原先的文件,读写文件,最后删除原先文件 剪切:先复制原先的文件,删除 ...
- mysql基础操作学习笔记(一)
1前期准备: SQL语言包涵以下4个部分: (1)数据定义语言(DDL):包括DROP, CREATE, ALTER等语句 (2)数据操纵语言(DML):包括INSERT, UPDATE, DELET ...
- spring ThreadPoolTaskExecutor使用总结
ThreadPoolTaskExecutor提供TaskDecorator可以实现类似ThreadPoolExecutor.afterExecute()类似功能 taskDecorator主要是对Ru ...
- 关于导入本地maven项目pom.xml出现missing artifact org....报错处理
一.导入本地maven项目步骤:
- SQL的CharIndex用法
和C#一样判断一个字符串中是否包含另一个字符串举例1:select charindex('test','This Test is test!!')->返回 6 (空格也算一个 下标从1开始)2: ...
- vue 路由更新页面视图未更新问题
最近项目做面包屑的时候遇到一个问题就是路由变化的时候页面视图并没有发生变化,后来上网查,发现是vue-router的特性导致的. vue-router的切换不同于传统的页面的切换.路由之间的切换,其实 ...
- 问题记录——com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
最近在搞一个Spring boot + Mybatis + Mysql的项目,用Mybatis访问数据库时,报了如下的错误,先在网上搜索了,试了各种办法都不行, 奇葩的是,连接另外1个数据库又没问题. ...