当前位置: 移动技术网 > IT编程>开发语言>.net > asp.net(C#)压缩图片,可以指定图片模板高宽

asp.net(C#)压缩图片,可以指定图片模板高宽

2017年12月12日  | 移动技术网IT编程  | 我要评论

尺井亮,张兆艺新浪微博,农民伯伯乡下妹快播

复制代码 代码如下:

//生成缩略图函数
//顺序参数:源图文件流、缩略图存放地址、模版宽、模版高
//注:缩略图大小控制在模版区域内
public static void makesmallimg(system.io.stream fromfilestream, string filesaveurl, system.double templatewidth, system.double templateheight)
{
//从文件取得图片对象,并使用流中嵌入的颜色管理信息
system.drawing.image myimage = system.drawing.image.fromstream(fromfilestream, true);
//缩略图宽、高
system.double newwidth = myimage.width, newheight = myimage.height;
//宽大于模版的横图
if (myimage.width > myimage.height || myimage.width == myimage.height)
{
if (myimage.width > templatewidth)
{
//宽按模版,高按比例缩放
newwidth = templatewidth;
newheight = myimage.height * (newwidth / myimage.width);
}
}
//高大于模版的竖图
else
{
if (myimage.height > templateheight)
{
//高按模版,宽按比例缩放
newheight = templateheight;
newwidth = myimage.width * (newheight / myimage.height);
}
}
//取得图片大小
system.drawing.size mysize = new size((int)newwidth, (int)newheight);
//新建一个bmp图片
system.drawing.image bitmap = new system.drawing.bitmap(mysize.width, mysize.height);
//新建一个画板
system.drawing.graphics g = system.drawing.graphics.fromimage(bitmap);
//设置高质量插值法
g.interpolationmode = system.drawing.drawing2d.interpolationmode.high;
//设置高质量,低速度呈现平滑程度
g.smoothingmode = system.drawing.drawing2d.smoothingmode.highquality;
//清空一下画布
g.clear(color.white);
//在指定位置画图
g.drawimage(myimage, new system.drawing.rectangle(0, 0, bitmap.width, bitmap.height),
new system.drawing.rectangle(0, 0, myimage.width, myimage.height),
system.drawing.graphicsunit.pixel);
///文字水印
//system.drawing.graphics g=system.drawing.graphics.fromimage(bitmap);
//system.drawing.font f=new font("宋体",10);
//system.drawing.brush b=new solidbrush(color.black);
//g.drawstring("myohmine",f,b,10,10);
//g.dispose();
///图片水印
//system.drawing.image copyimage = system.drawing.image.fromfile(system.web.httpcontext.current.server.mappath("pic/1.gif"));
//graphics a = graphics.fromimage(bitmap);
//a.drawimage(copyimage, new rectangle(bitmap.width-copyimage.width,bitmap.height-copyimage.height,copyimage.width, copyimage.height),0,0, copyimage.width, copyimage.height, graphicsunit.pixel);
//copyimage.dispose();
//a.dispose();
//copyimage.dispose();
//保存缩略图
bitmap.save(filesaveurl, system.drawing.imaging.imageformat.jpeg);
g.dispose();
myimage.dispose();
bitmap.dispose();
}

复制代码 代码如下:

private void button2_click(object sender, eventargs e)
{
openfiledialog filedialog = new openfiledialog();
filedialog.title = "选择图片文件";
// filedialog.filter = "excel files (*.xls)|*.xls";
filedialog.filterindex = 1;
if (filedialog.showdialog() == system.windows.forms.dialogresult.ok)
{

system.io.filestream file =system.io.file.open(filedialog.filename,system.io.filemode.open);
system.io.stream strea = file;
file.close();
makesmallimg(strea, "缩略图.jpg", 150, 150);
// file.close();

}
}

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网