/// <summary>
/// 生成jpg缩略图字节,本人的小软件中需要用到的功能,所以自己做了一个函数,和大家分享
/// 为什么要生成字节而不是文件,这是为了方便后续处理啦^_^
/// </summary>
/// <param name="originalimagepath">原始路径</param>
/// <param name="quality">质量0-100</param>
/// <param name="width">宽度</param>
/// <param name="height">高度</param>
/// <param name="mode">模式:hw,w,h,cut</param>
/// <returns></returns>
public static byte[] makejpgthumbnailbytes(string originalimagepath, long quality, int width, int height, string mode)
{
image originalimage = image.fromfile(originalimagepath);
memorystream s = new memorystream();
int towidth = width;
int toheight = height;
int x = 0;
int y = 0;
int ow = originalimage.width;
int oh = originalimage.height;
switch (mode)
{
case "hw"://指定高宽缩放(可能变形)
break;
case "w"://指定宽,高按比例
toheight = originalimage.height * width / originalimage.width;
break;
case "h"://指定高,宽按比例
towidth = originalimage.width * height / originalimage.height;
break;
case "cut"://指定高宽裁减(不变形)
if ((double)originalimage.width / (double)originalimage.height > (double)towidth / (double)toheight)
{
oh = originalimage.height;
ow = originalimage.height * towidth / toheight;
y = 0;
x = (originalimage.width - ow) / 2;
}
else
{
ow = originalimage.width;
oh = originalimage.width * height / towidth;
x = 0;
y = (originalimage.height - oh) / 2;
}
break;
default:
break;
}
//新建一个bmp图片
image bitmap = new system.drawing.bitmap(towidth, toheight);
//新建一个画板
graphics g = system.drawing.graphics.fromimage(bitmap);
//设置高质量插值法
g.interpolationmode = system.drawing.drawing2d.interpolationmode.high;
//设置高质量,低速度呈现平滑程度
g.smoothingmode = system.drawing.drawing2d.smoothingmode.highquality;
//清空画布并以透明背景色填充
g.clear(color.transparent);
//在指定位置并且按指定大小绘制原图片的指定部分
g.drawimage(originalimage, new rectangle(0, 0, towidth, toheight),
new rectangle(x, y, ow, oh),
graphicsunit.pixel);
try
{
//以jpg格式保存缩略图
encoderparameters eps = new encoderparameters(1);
encoderparameter ep = new encoderparameter(encoder.quality,quality);
eps.param[0] = ep;
bitmap.save(s, getcodecinfo("image/jpeg"), eps);
return s.getbuffer();
}
catch (system.exception e)
{
throw e;
}
finally
{
originalimage.dispose();
bitmap.dispose();
s.dispose();
g.dispose();
}
}
/**/
/// <summary>
/// 保存jpg时用
/// </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;
}
如对本文有疑问,
点击进行留言回复!!
相关文章:
-
-
C#实现猜数字游戏
本文实例为大家分享了c#实现猜数字游戏具体代码,供大家参考,具体内容如下给定一个0-100的随机数字猜其大小题目样式:电脑产生一个0到100之间的随机数字,并且...
[阅读全文]
-
-
C# 可空类型的具体使用
在项目中我们经常会遇到可为空类型,那么到底什么是可为空类型呢?下面我们将从4个方面为大家剖析。1、可空类型基础知识顾名思义,可空类型指的就是某个对象类型可以为空...
[阅读全文]
-
-
-
C#实现猜数字小游戏
本文实例为大家分享了c#实现猜数字小游戏的具体代码,供大家参考,具体内容如下效果如图:代码:using system;using system.collecti...
[阅读全文]
-
-
C#实现简单俄罗斯方块
最近在看《.net游戏编程入门经典 c#篇》 第一章介绍了如何制作俄罗斯方块,自己试了试按照书上的步骤,可算是完成了。于是写下这篇文章留作纪念。1.类的设计在充...
[阅读全文]
-
-
网友评论