压缩图片或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提供现有的图像文件和图像对象的类中简化了处理过程,两三行代码就能够从现有图片生 ...
随机推荐
- eclipse 创建maven
下载地址自行搜索关键字:“eclipse官网”即可,注意下版本,32bit or 64bit. maven插件以及svn等相关插件安装设置问题不在这里赘述,有时间的话会发布出来. 在这里说一下,第一. ...
- commons工具类
转自:https://blog.csdn.net/leaderway/article/details/52387925 1.1. 开篇 在Java的世界,有很多(成千上万)开源的框架,有成功的,也有不 ...
- 中文 bootstrapValidator
官网地址:http://bassistance.de/jquery-plugins/jquery-plugin-validation jQuery plugin: Validation 使用说明 转载 ...
- WordCount(JAVA实现)
201631103228,201631101227 1.项目需求 对程序设计语言源文件统计字符数.单词数.行数,统计结果以指定格式输出到默认文件中,以及其他扩展功能,并能够快速地处理多个文件. wc. ...
- HTML中DOM元素的子节点为空?!firstChild, lastChild, childeNodes[]为空
- “全栈2019”Java第十一章:标识符
难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java第 ...
- flask内置函数 send_static_file(filename)
内部使用的函数将静态文件从静态文件夹发送到浏览器. current_app.send_static_file(filename)
- Mondrian Schema Workbench 概念及常用参数
Schema Schema 定义了一个多维数据库.包含了一个逻辑模型,而这个逻辑模型的目的是为了书写 MDX 语言的查询语句.这个逻辑模型实际上提供了这几个概念: Cubes (立方体).维度( Di ...
- day0201
#1.使用while循环输入 1 2 3 4 5 6 8 9 10'''count = 0while count < 10: count += 1 # count = count + 1 if ...
- 纯css使div垂直居中,div垂直,div居中的方法
首先编写一个简单的html代码,设置一个父div类名为boxFather,再设置一个子div类名为box1.html代码如下: <div class="boxFather"& ...