欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#实现图片切割的方法

程序员文章站 2023-11-17 10:24:46
本文实例讲述了c#实现图片切割的方法。分享给大家供大家参考,具体如下: 图片切割就是把一幅大图片按用户要求切割成多幅小图片。dotnet环境下系统提供了gdi+类库,为图...

本文实例讲述了c#实现图片切割的方法。分享给大家供大家参考,具体如下:

图片切割就是把一幅大图片按用户要求切割成多幅小图片。dotnet环境下系统提供了gdi+类库,为图像操作处理提供了方便的接口。

下面是图像切割小程序:

public class imagemanager
{
  /// <summary>
  /// 图像切割
  /// </summary>
  /// <param name="url">图像文件名称</param>
  /// <param name="width">切割后图像宽度</param>
  /// <param name="height">切割后图像高度</param>
  /// <param name="savepath">切割后图像文件保存路径</param>
  /// <param name="fileext">切割后图像文件扩展名</param>
  public static void cut(string url, int width, int height,string savepath,string fileext,string logofile)
  {
   bitmap bitmap = new bitmap(url);
   decimal maxrow = math.ceiling((decimal)bitmap.height / height);
   decimal maxcolumn = math.ceiling((decimal)bitmap.width / width);
   for (decimal i = 0; i < maxrow; i++)
   {
    for (decimal j = 0; j < maxcolumn; j++)
    {
     string filename = i.tostring() + "," + j.tostring() + "." + fileext;
     bitmap bmp = new bitmap(width, height);
     for (int offsetx = 0; offsetx < width; offsetx++)
     {
      for (int offsety = 0; offsety < height; offsety++)
      {
       if (((j * width + offsetx) < bitmap.width) && ((i * height + offsety) < bitmap.height))
       {
        bmp.setpixel(offsetx, offsety, bitmap.getpixel((int)(j * width + offsetx), (int)(i * height + offsety)));
       }
      }
     }
     graphics g = graphics.fromimage(bmp);
     g.drawstring("", new font("黑体", 20), new solidbrush(color.fromargb(70, color.whitesmoke)), 60, height/2);//加水印
     imageformat format = imageformat.png;
     switch (fileext.tolower())
     {
      case "png":
       format = imageformat.png;
       break;
      case "bmp":
       format = imageformat.bmp;
       break;
      case "gif":
       format = imageformat.gif;
       break;
     }
     bmp.save(savepath+"//" + filename,format);
    }
   }
  }
}

程序员只需要调用cut函数就可以应用了。

更多关于c#相关内容感兴趣的读者可查看本站专题:《c#图片操作技巧汇总》、《c#常见控件用法教程》、《winform控件用法总结》、《c#数据结构与算法教程》、《c#面向对象程序设计入门教程》及《c#程序设计之线程使用技巧总结

希望本文所述对大家c#程序设计有所帮助。