c#不改变图像长宽比例调整图像大小
在ui显示图片时,如果容器大小固定,而图片尺寸大于容器,那显示图片时会显示不全。
有些容器(例如picturebox)本身可以通过设置属性来改变图像大小,让图像大小自动适应容器,但这不能保证图像的长宽比例不变。
这时,我们可以通过编码计算长宽来重绘图像。
c#代码
如下:
/// <summary> /// 根据容器(如picturebox)长宽的限制,在不改变图像比例的情况下,调整图像大小 /// author:huangyq1984@qq.com /// </summary> /// <param name="maxwidth">容器宽</param> /// <param name="maxheight">容器高</param> /// <param name="srcimg">原图</param> /// <param name="backcolor">空白处的背景色</param> /// <returns></returns> public static image getimagetofitcontainer(int maxwidth,int maxheight, image srcimg, color backcolor) { if (srcimg == null) return null; float scale; int iw, ih; //计算原图的长宽比例 scale = (float)srcimg.height / (float)srcimg.width; iw = srcimg.width; ih = srcimg.height; //如果原图长宽都不大于容器长和宽,则不需要调整大小 if (srcimg.width <= maxwidth && srcimg.height <= maxheight) { iw = srcimg.width; ih = srcimg.height; } //如果原图宽大于容器宽,且原图高不大于容器高,则调整后的图像宽就是容器宽,图像高需要根据长宽比例来计算 else if (srcimg.width > maxwidth && srcimg.height <= maxheight) { iw = maxwidth; ih = (int)(scale * iw); } //如果原图高大于容器高,且原图宽不大于容器宽,则调整后的图像高就是容器高,图像宽需要根据长宽比例来计算 else if (srcimg.width <= maxwidth && srcimg.height > maxheight) { ih = maxheight; iw = (int)(ih / scale); } //如果原图高和宽都大于容器高和宽,则调整后的图像高和图像宽都需要重新计算 else if (srcimg.width > maxwidth && srcimg.height > maxheight) { iw = maxwidth; ih = (int)(scale * iw); if (ih > maxheight) { ih = maxheight; iw = (int)(ih / scale); } } //构建新的位图 bitmap bmp = new bitmap(iw, ih); graphics g = graphics.fromimage(bmp); //用背景色填充 g.clear(backcolor); //在位图上根据调整后的高和宽绘制原图 g.drawimage(srcimg, 0, 0, iw, ih); //保存 system.io.memorystream ms = new system.io.memorystream(); bmp.save(ms, system.drawing.imaging.imageformat.jpeg); g.dispose(); srcimg = (image)bmp; return srcimg; }
c#winform前端调用
如下:
image srcimage = image.fromfile(filename); picturebox1.sizemode = pictureboxsizemode.centerimage; picturebox1.image = getimagetofitcontainer(picturebox1.width,picturebox1.height,srcimage,color.transparent);
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论