当前位置: 移动技术网 > IT编程>开发语言>.net > C#根据屏幕分辨率改变图片尺寸

C#根据屏幕分辨率改变图片尺寸

2018年11月01日  | 移动技术网IT编程  | 我要评论

网络电话资费,雪山圣乳,酢狗

最近工作中遇到一个问题,就是需要将程序文件夹中的图片根据此时电脑屏幕的分辨率来重新改变图片尺寸

以下为代码实现过程:

1、获取文件夹中的图片,此文件夹名为exe程序同目录下

//读取文件夹中文件
directoryinfo dir = new directoryinfo(@"文件夹名");
fileinfo[] fileinfo = dir.getfiles();
 list<string> filenames = new list<string>();
foreach (fileinfo item in fileinfo)
{
    filenames.add(item.name);
}

2、获取电脑屏幕分辩率

//获取全屏下屏幕分辩率
rectangle rect = new rectangle();
//全屏
rect.width = (int)system.windows.systemparameters.primaryscreenwidth;
rect.height = (int)system.windows.systemparameters.primaryscreenheight;
//rect = screen.getworkingarea(this);//工作区域下的分辩率,不包括任务栏
//rect.width;//屏幕宽
//rect.height;//屏幕高 

3、改变图片尺寸,并保存

/// <summary>
/// 生成缩略图
/// </summary>
/// <param name="serverimagepath">图片地址</param>
/// <param name="thumbnailimagepath">缩略图地址</param>
/// <param name="width">图片宽度</param>
/// <param name="height">图片高度</param>
/// <param name="p"></param>
public static void getthumbnail(string serverimagepath, string thumbnailimagepath, int width, int height)
{
    system.drawing.image serverimage = system.drawing.image.fromfile(serverimagepath);
    //画板大小
    int towidth = width;
    int toheight = height;
    //缩略图矩形框的像素点
    int ow = serverimage.width;
    int oh = serverimage.height;

    if (ow > oh)
    {
        toheight = serverimage.height * width / serverimage.width;
    }
    else
    {
        towidth = serverimage.width * height / serverimage.height;
    }
    //新建一个bmp图片
    system.drawing.image bm = new system.drawing.bitmap(width, height);
    //新建一个画板
    system.drawing.graphics g = system.drawing.graphics.fromimage(bm);
    //设置高质量插值法
    g.interpolationmode = system.drawing.drawing2d.interpolationmode.high;
    //设置高质量,低速度呈现平滑程度
    g.smoothingmode = system.drawing.drawing2d.smoothingmode.highquality;
    //清空画布并以透明背景色填充
    g.clear(system.drawing.color.white);
    //在指定位置并且按指定大小绘制原图片的指定部分
    g.drawimage(serverimage, new system.drawing.rectangle((width - towidth) / 2, (height - toheight) / 2, towidth, toheight),
        0, 0, ow, oh,
        system.drawing.graphicsunit.pixel);
    try
    {
        //以jpg格式保存缩略图
        bm.save(thumbnailimagepath, system.drawing.imaging.imageformat.jpeg);
    }
    catch (system.exception e)
    {
        throw e;
    }
    finally
    {
        serverimage.dispose();
        bm.dispose();
        g.dispose();
    }
}

自此整个功能就实现了。

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

相关文章:

验证码:
移动技术网