文件上传,服务端压缩文件方法,重点是png与gif图片的压缩,保证了透明度与动画
/// <summary>
/// 上传文件帮助类
/// </summary>
public class ImageUploadHelper
{ #region SaveVideoFirstImg 根据视频路径生成视频对应的图片
/// <summary>
/// 根据视频路径生成视频对应的图片
/// </summary>
/// <param name="videoUrl">视频的绝对路径</param>
public static void SaveVideoFirstImg(string videoUrl)
{
var saveFileurl = videoUrl.Substring(, videoUrl.LastIndexOf(".")) + ".jpg";
Process p = new Process();
p.StartInfo.FileName = string.Format("{0}\\ffmpeg.exe", HttpContext.Current.Server.MapPath("~/media/"));
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.Arguments = string.Format("-i {0} -y -f image2 -t 1 {1}", videoUrl, saveFileurl);
p.Start();
p.WaitForExit();
p.Close();
p.Dispose();
}
#endregion #region CompressImg 生成缩略图方法
/// <summary>
/// 生成缩略图方法
/// </summary>
/// <param name="oldUrl">完整原始图片路径</param>
/// <param name="newUrl">完整缩略图路径</param>
/// <param name="thumbWidth">缩略图宽度</param>
/// <param name="thumbHeight">缩略图高度</param>
/// <returns>成功生成返回true,失败生成返回false</returns>
public static bool CompressImg(string oldUrl, string newUrl, double thumbWidth, double thumbHeight)
{
if (File.Exists(oldUrl))
{
//原图加载
using (System.Drawing.Image sourceImage = System.Drawing.Image.FromFile(oldUrl))
{
var imgFormate = GetImageFormat(sourceImage); //原图宽高均小于模版,不作处理,直接保存
if (sourceImage.Width <= thumbWidth && sourceImage.Height <= thumbHeight)
{
//保存
sourceImage.Save(newUrl, imgFormate);
}
else
{
//缩略图宽、高计算
double newWidth = sourceImage.Width;
double newHeight = sourceImage.Height; //宽大于高或宽等于高(横图或正方)
if (sourceImage.Width >= sourceImage.Height)
{
//如果宽大于模版
if (sourceImage.Width > thumbWidth)
{
//宽按模版,高按比例缩放
newWidth = thumbWidth;
newHeight = sourceImage.Height * (thumbWidth / sourceImage.Width);
}
}
//高大于宽(竖图)
else
{
//如果高大于模版
if (sourceImage.Height > thumbHeight)
{
//高按模版,宽按比例缩放
newHeight = thumbHeight;
newWidth = sourceImage.Width * (thumbHeight / sourceImage.Height);
}
} //判断是否为gif或者tiff图片
if (imgFormate == ImageFormat.Gif || imgFormate == ImageFormat.Tiff)
{
//压缩图片
CompressImgGif(sourceImage, imgFormate, newUrl, (int)newWidth, (int)newHeight);
}
else //其它格式图片
{
//生成新图,新建一个bmp图片
System.Drawing.Image newImage = new System.Drawing.Bitmap((int)newWidth, (int)newHeight); //新建一个画板
System.Drawing.Graphics newG = System.Drawing.Graphics.FromImage(newImage); //置背景色
newG.Clear(Color.Transparent); //设置质量
newG.InterpolationMode = InterpolationMode.HighQualityBicubic;
newG.SmoothingMode = SmoothingMode.HighQuality; //画图
newG.DrawImage(sourceImage, new System.Drawing.Rectangle(, , newImage.Width, newImage.Height), new System.Drawing.Rectangle(, , sourceImage.Width, sourceImage.Height), System.Drawing.GraphicsUnit.Pixel); newImage.Save(newUrl, imgFormate); //释放资源
newG.Dispose();
newImage.Dispose();
}
}
}
return true;
} return false;
}
#endregion #region CompressImgGif 压缩gif图片
/// <summary>
/// 压缩gif图片
/// </summary>
/// <param name="oldUrl"></param>
/// <param name="newUrl"></param>
/// <param name="thumbWidth"></param>
/// <param name="thumbHeight"></param>
public static void CompressImgGif(Image sourceImage, ImageFormat format, string newUrl, int width, int height)
{
//新图第一帧
Image new_img = new Bitmap(width, height); //新图其他帧
Image new_imgs = new Bitmap(width, height); //新图第一帧GDI+绘图对象
Graphics g_new_img = Graphics.FromImage(new_img); //新图其他帧GDI+绘图对象
Graphics g_new_imgs = Graphics.FromImage(new_imgs); //配置新图第一帧GDI+绘图对象
g_new_img.CompositingMode = CompositingMode.SourceCopy;
g_new_img.InterpolationMode = InterpolationMode.HighQualityBicubic;
g_new_img.PixelOffsetMode = PixelOffsetMode.HighQuality;
g_new_img.SmoothingMode = SmoothingMode.HighQuality;
g_new_img.Clear(Color.FromKnownColor(KnownColor.Transparent)); //配置其他帧GDI+绘图对象
g_new_imgs.CompositingMode = CompositingMode.SourceCopy;
g_new_imgs.InterpolationMode = InterpolationMode.HighQualityBicubic;
g_new_imgs.PixelOffsetMode = PixelOffsetMode.HighQuality;
g_new_imgs.SmoothingMode = SmoothingMode.HighQuality;
g_new_imgs.Clear(Color.FromKnownColor(KnownColor.Transparent)); //遍历维数
foreach (Guid gid in sourceImage.FrameDimensionsList)
{
//因为是缩小GIF文件所以这里要设置为Time
//如果是TIFF这里要设置为PAGE
FrameDimension f = format == ImageFormat.Gif ? FrameDimension.Time : FrameDimension.Page; //获取总帧数
int count = sourceImage.GetFrameCount(f);
//保存标示参数
System.Drawing.Imaging.Encoder encoder = System.Drawing.Imaging.Encoder.SaveFlag;
//
EncoderParameters ep = null; //每一帧
for (int c = ; c < count; c++)
{
//选择由维度和索引指定的帧
sourceImage.SelectActiveFrame(f, c);
//第一帧
if (c == )
{
//将原图第一帧画给新图第一帧
g_new_img.DrawImage(sourceImage, new Rectangle(, , new_img.Width,new_img.Height), new Rectangle(, , sourceImage.Width, sourceImage.Height), GraphicsUnit.Pixel); //把振频和透明背景调色板等设置复制给新图第一帧
for (int i = ; i < sourceImage.PropertyItems.Length; i++)
{
new_img.SetPropertyItem(sourceImage.PropertyItems[i]);
}
ep = new EncoderParameters();
//第一帧需要设置为MultiFrame
ep.Param[] = new EncoderParameter(encoder, (long)EncoderValue.MultiFrame); //保存第一帧
new_img.Save(newUrl, GetCodecInfo(format.Guid), ep);
}
//其他帧
else
{
//把原图的其他帧画给新图的其他帧
g_new_imgs.DrawImage(sourceImage, new Rectangle(, , new_imgs.Width,new_imgs.Height), new Rectangle(, , sourceImage.Width, sourceImage.Height), GraphicsUnit.Pixel); //把振频和透明背景调色板等设置复制给新图第一帧
for (int i = ; i < sourceImage.PropertyItems.Length; i++)
{
new_imgs.SetPropertyItem(sourceImage.PropertyItems[i]);
}
ep = new EncoderParameters(); //如果是GIF这里设置为FrameDimensionTime
//如果为TIFF则设置为FrameDimensionPage
ep.Param[] = new EncoderParameter(encoder, (long)(format == ImageFormat.Gif ? EncoderValue.FrameDimensionTime : EncoderValue.FrameDimensionPage)); //向新图添加一帧
new_img.SaveAdd(new_imgs, ep);
}
} ep = new EncoderParameters();
//关闭多帧文件流
ep.Param[] = new EncoderParameter(encoder, (long)EncoderValue.Flush);
new_img.SaveAdd(ep);
} //释放文件
new_img.Dispose();
new_imgs.Dispose();
g_new_img.Dispose();
g_new_imgs.Dispose();
}
#endregion #region 压缩文件
/// <summary>
/// 压缩文件
/// </summary>
/// <param name="oldImg"></param>
/// <param name="newImg"></param>
public static void CompressSize(string oldImg, string newImg)
{ using (System.Drawing.Image sourceImage = System.Drawing.Image.FromFile(oldImg))
{
Bitmap bmp = new Bitmap(sourceImage);
KiSaveAsJPEG(bmp, newImg, );
} } //// <summary>
/// 保存为JPEG格式,支持压缩质量选项
/// </summary>
/// <param name="bmp"></param>
/// <param name="FileName"></param>
/// <param name="Qty"></param>
/// <returns></returns>
public static bool KiSaveAsJPEG(Bitmap bmp, string FileName, int Qty)
{
try
{
EncoderParameter p;
EncoderParameters ps; ps = new EncoderParameters(); p = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, Qty);
ps.Param[] = p; bmp.Save(FileName, GetCodecInfo("image/jpeg"), ps); return true;
}
catch
{
return false;
}
} //// <summary>
/// 获取codeinfo
/// </summary>
/// <param name="mimeType"></param>
/// <returns>得到指定mimeType的ImageCodecInfo</returns>
private static ImageCodecInfo GetCodecInfo(string mimeType)
{
ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
foreach (ImageCodecInfo ici in CodecInfo)
{
if (ici.MimeType == mimeType) return ici;
}
return null;
} /// <summary>
/// 获取codeinfo
/// </summary>
/// <param name="guid"></param>
/// <returns></returns>
public static ImageCodecInfo GetCodecInfo(Guid guid)
{
ImageCodecInfo[] icis = ImageCodecInfo.GetImageDecoders(); //为 图片编码、解码器 对象 赋值
foreach (ImageCodecInfo ici in icis)
{
if (ici.FormatID == guid)
{
return ici;
}
} return null;
}
#endregion #region GetImageFormat 获取图片文件格式
/// <summary>
/// 获取图片文件格式
/// </summary>
/// <param name="img"></param>
/// <returns></returns>
public static ImageFormat GetImageFormat(Image img)
{
if (img != null)
{
ImageFormat fileExtension = img.RawFormat,
jpgExtension = ImageFormat.Jpeg,
gifExtension = ImageFormat.Gif,
pngExtension = ImageFormat.Png,
iconExtension = ImageFormat.Icon,
bmpExtension = ImageFormat.Bmp,
tiffExtension = ImageFormat.Tiff,
wmfExtension = ImageFormat.Wmf,
emfExtension = ImageFormat.Emf,
exifExtension = ImageFormat.Exif; if (fileExtension.Equals(jpgExtension))
{
return ImageFormat.Jpeg;
}
else if (fileExtension.Equals(gifExtension))
{
return ImageFormat.Gif;
}
else if (fileExtension.Equals(pngExtension))
{
return ImageFormat.Png;
}
else if (fileExtension.Equals(iconExtension))
{
return ImageFormat.Icon;
}
else if (fileExtension.Equals(bmpExtension))
{
return ImageFormat.Bmp;
}
else if (fileExtension.Equals(tiffExtension))
{
return ImageFormat.Tiff;
}
else if (fileExtension.Equals(wmfExtension))
{
return ImageFormat.Wmf;
}
else if (fileExtension.Equals(emfExtension))
{
return ImageFormat.Emf;
}
else if (fileExtension.Equals(exifExtension))
{
return ImageFormat.Exif;
}
}
return ImageFormat.Jpeg;
}
#endregion #region GetExtension 获得上传文件的扩展名
/// <summary>
/// 获得上传文件的扩展名
/// </summary>
/// <param name="img"></param>
/// <returns></returns>
public static string GetExtension(Image img)
{
if (img != null)
{
ImageFormat fileExtension = img.RawFormat,
jpgExtension = ImageFormat.Jpeg,
gifExtension = ImageFormat.Gif,
pngExtension = ImageFormat.Png,
iconExtension = ImageFormat.Icon,
bmpExtension = ImageFormat.Bmp,
tiffExtension = ImageFormat.Tiff,
wmfExtension = ImageFormat.Wmf,
emfExtension = ImageFormat.Emf,
exifExtension = ImageFormat.Exif; if (fileExtension.Equals(jpgExtension))
{
return ".jpg";
}
else if (fileExtension.Equals(gifExtension))
{
return ".gif";
}
else if (fileExtension.Equals(pngExtension))
{
return ".png";
}
else if (fileExtension.Equals(iconExtension))
{
return ".icon";
}
else if (fileExtension.Equals(bmpExtension))
{
return ".bmp";
}
else if (fileExtension.Equals(tiffExtension))
{
return ".tiff";
}
else if (fileExtension.Equals(wmfExtension))
{
return ".wmf";
}
else if (fileExtension.Equals(emfExtension))
{
return ".emf";
}
else if (fileExtension.Equals(exifExtension))
{
return ".exif";
}
}
return ".jpg";
}
#endregion } #region UploadImageMsg 上传图片后返回上传结果
/// <summary>
/// 上传图片后返回上传结果
/// </summary>
public class UploadImageMsg
{
public UploadImageMsg()
{
error = ;
url = message = string.Empty;
} /// <summary>
/// 1错误 0成功
/// </summary>
public int error { get; set; }
/// <summary>
/// 错误信息
/// </summary>
public string message { get; set; }
/// <summary>
/// 上传成功的url路径
/// </summary>
public string url { get; set; }
}
#endregion
文件上传,服务端压缩文件方法,重点是png与gif图片的压缩,保证了透明度与动画的更多相关文章
- nodejs 文件上传服务端实现
前段时间在做个人项目的时候,用到了nodejs服务端上传文件,现在回头把这个小结一下,作为记录. 本人上传文件时是基于express的multiparty,当然也可以使用connect-multipa ...
- PHP 文件上传服务端及客户端配置参数说明
文件上传服务器端配置: ·file_uploads = On, 支持HTTP上传 ·upload_tmp_dir = , 临时文件保存的目录 ·upload_max_filesize=2M, 允许上传 ...
- web安全之文件上传漏洞攻击与防范方法
一. 文件上传漏洞与WebShell的关系 文件上传漏洞是指网络攻击者上传了一个可执行的文件到服务器并执行.这里上传的文件可以是木马,病毒,恶意脚本或者WebShell等.这种攻击方式是最为直接和有效 ...
- 构建基于阿里云OSS文件上传服务
转载请注明来源:http://blog.csdn.net/loongshawn/article/details/50710132 <构建基于阿里云OSS文件上传服务> <构建基于OS ...
- Java FtpClient 实现文件上传服务
一.Ubuntu 安装 Vsftpd 服务 1.安装 sudo apt-get install vsftpd 2.添加用户(uftp) sudo useradd -d /home/uftp -s /b ...
- php文件上传大小限制的修改方法大全
php文件上传大小限制的修改方法大全 基本就是修改maxsize选项,当然为了提高上传文件的成功率,还需要设置超时时间等. 文章如下: [php文件上传]php文件上传大小限制修改,phpmyadmi ...
- django设置并获取cookie/session,文件上传,ajax接收文件,post/get请求及跨域请求等的方法
django设置并获取cookie/session,文件上传,ajax接收文件等的方法: views.py文件: from django.shortcuts import render,HttpRes ...
- HTTP文件上传服务器-支持超大文件HTTP断点续传的实现办法
最近由于笔者所在的研发集团产品需要,需要支持高性能的大文件http上传,并且要求支持http断点续传.笔者在以前的博客如何实现支持大文件的高性能HTTP文件上传服务器已经介绍了实现大文件上传的一些基本 ...
- 精讲RestTemplate第6篇-文件上传下载与大文件流式下载
本文是精讲RestTemplate第6篇,前篇的blog访问地址如下: 精讲RestTemplate第1篇-在Spring或非Spring环境下如何使用 精讲RestTemplate第2篇-多种底层H ...
- php 文件上传后缀名与文件类型对照表(几乎涵盖所有文件)
网上有很多php文件上传的类,文件上传处理是php的一个特色(至少手册上是将此作为php特点来展示的,个人认为php在数组方面的优异功能更有特 色),学php的人都知道文件上传怎么做,但很多人在编程中 ...
随机推荐
- hadoop2.7.3+spark2.1.0+scala2.12.1环境搭建(4)SPARK 安装
hadoop2.7.3+spark2.1.0+scala2.12.1环境搭建(4)SPARK 安装 一.依赖文件安装 1.1 JDK 参见博文:http://www.cnblogs.com/liugh ...
- JVM 性能调优监控工具
声明:本文转自<https://www.cnblogs.com/anxiao/p/6796644.html?utm_source=itdadao&utm_medium=referral& ...
- Java-NIO(四):通道(Channel)的原理与获取
通道(Channel): 由java.nio.channels包定义的,Channel表示IO源与目标打开的连接,Channel类似于传统的“流”,只不过Channel本身不能直接访问数据,Chann ...
- 【图解数据结构】 栈&队列
[TOC] 勤于总结,持续输出! 1.栈 1.1栈的定义 栈(stack)是限定在表尾进行插入和删除的操作的线性表. 我们把允许插入和删除的一端称为栈顶(top),另一端称为栈底(bottom),不包 ...
- C++因继承引发的隐藏与重写
在区分隐藏和重写之前,先来理一理关于继承的东西... [继承] 继承是面向对象复用的重要手段.通过继承定义一个类,继承是类型之间的关系建模,共享公有的东西,实现各自本质不同的东西.简单的说,继承就是指 ...
- [LeetCode] Two Sum IV - Input is a BST 两数之和之四 - 输入是二叉搜索树
Given a Binary Search Tree and a target number, return true if there exist two elements in the BST s ...
- [LeetCode] Most Frequent Subtree Sum 出现频率最高的子树和
Given the root of a tree, you are asked to find the most frequent subtree sum. The subtree sum of a ...
- spark-shell报错:Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/hadoop/fs/FSDataInputStream
环境: openSUSE42.2 hadoop2.6.0-cdh5.10.0 spark1.6.0-cdh5.10.0 按照网上的spark安装教程安装完之后,启动spark-shell,出现如下报错 ...
- [测试题]line
Description Input Output Sample Input 10 49743636 36679 707182 9310618 9814768 2315242 9916077 35233 ...
- 【NOIP模拟赛】总结
题目描述 输入 第一行是5个正整数,n,m,k,S,T,分别代表无向图点数,边数,蝙蝠的数量,二小姐所在起点的编号,目标点的编号. 第二行是k个正整数,分别代表大小姐每个蝙蝠所在的起点的编号.接下来有 ...