压缩图片或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提供现有的图像文件和图像对象的类中简化了处理过程,两三行代码就能够从现有图片生 ...
随机推荐
- struts2把表单数据封装到实体类里
<form method="post" action=""> <input type="text" name=" ...
- 「HNOI 2015」菜肴制作
题目链接 戳我 \(Description\) 有若干限制,需要求一个\(1\)到\(n\)的排列,每个限制\((x,y)\)表示\(x\)必须在\(j\)之前,并要求所求的排列满足所有限制并让\(1 ...
- 【题解】 [NOI1999]生日蛋糕
题面 传送门 Solution 搜索每一层的半径和高度,然后加入一些剪枝就好了. #include<stdio.h> #include<stdlib.h> #include&l ...
- 《Beginning Java 7》 - 4 - finalize() 手动垃圾回收
当我们想在系统进行垃圾回收时做一些特定的工作,我们就可以重写 finalze() 函数,因为 Object 的 此函数是空的. 比如: protected void finalize() throws ...
- 【bzoj 3595】: [Scoi2014]方伯伯的Oj
传送门&& 原题解 蒟蒻终于做到一道方伯伯的题了…… 调了一个上午一直TLE(发现自己打了好久的splay板子竟然是错的这种丢人事情我就不说了) 很明显,要建两棵树,$T1$维护排名, ...
- jquery源码解析:jQuery静态属性对象support详解
jQuery.support是用功能检测的方法来检测浏览器是否支持某些功能.针对jQuery内部使用. 我们先来看一些源码: jQuery.support = (function( support ) ...
- jquery源码解析:jQuery扩展方法extend的详解
jQuery中要扩展方法或者属性都是通过extend方法实现的.所谓的jQuery插件也是通过extend方法实现的. jQuery.extend扩展的是工具方法,也就是静态方法.jQuery.fn. ...
- Python常用功能函数
Python常用功能函数汇总 1.按行写字符串到文件中 import sys, os, time, json def saveContext(filename,*name): format = '^' ...
- HTML-★★★★★JavaScritp简介与语法★★★★★
简介: 1.什么是JavaScript? 它是个脚本语言,作用是使 HTML 页面具有更强的动态和交互性,它需要有宿主文件,它的宿主文件就是html文件. JavaScript 是 Web 的编程语 ...
- 1. java 的访问修饰符
一.什么情况下使用修饰符 属性通常使用private封装起来 方法一般使用public用于被调用 会被子类继承的方法,通常使用protected private protected package p ...