65.9K
CodeProject 正在变化。 阅读更多。
Home

图像文件生成器

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.61/5 (11投票s)

2007年3月5日

CPOL

1分钟阅读

viewsIcon

35885

downloadIcon

325

一个快速创建不透明或透明图像文件(*.GIF、*.PNG 等)的实用工具。

Screenshot - ImageFileBuilder.png

引言

如果您需要快速构建一个小型、简单的图像文件,此实用工具可以使其变得非常容易。图像文件可以是透明的、半透明的或不透明的(任何颜色),并且可以小至 1 像素 x 1 像素。图像文件可以保存为 GIF、JPEG、PNG、TIF 等。

背景

时不时地,对于一个 Web 项目或 WinForms 项目,您需要创建一个图像文件,也许是一个 1x16_transparent.png 或一个 32x16_red.gif 或一个 100x1_blue.jpeg。创建这些图像的方法有很多。ImageFileBuilder,也许是一个听起来有些自大的名字,只是让我的生活变得轻松了一些。

使用代码

如果您拥有 Visual Studio 2005,那么您应该能够“开箱即用”地使用项目源代码——只需构建并运行即可。代码本身并非什么高深的技术。它有合理的文档。对于 Bitmap 新手来说,代码的一个额外好处是,它向您展示了如何创建 Bitmap、如何为其着色以及如何使用 ImageFormat 枚举来以与请求的文件扩展名匹配的格式保存文件的简单示例。

创建具有给定颜色的 Bitmap 的代码

public Bitmap CreateBitmap(int width, int height, Color clr)
{
  try
  {
      Bitmap bmp = new Bitmap(width, height);

      for (int y = 0; y < bmp.Height; y++)
      {
          for (int x = 0; x < bmp.Width; x++)
          {
              bmp.SetPixel(x, y, clr);
          }
      }

      return bmp;
  }
  catch (Exception ex)
  {
      this.DoUpdateErrorMsg(ex.ToString());
      Debug.WriteLine(ex.ToString());
      return null;
  }
}

使用不同文件类型保存 Bitmap 的代码

public bool SaveBitmap(Bitmap bmp, string sOutputFilename)
{
  bool bRet = false;
  try
  {
      FileInfo fiOutputFile = new FileInfo(sOutputFilename);

      //determine the image format from the file name
      ImageFormat imgFmtWant = ImageFormat.Png;
      switch (fiOutputFile.Extension.ToUpper())
      {
          case ".BMP" : imgFmtWant = ImageFormat.Bmp; break;
          case ".EMF" : imgFmtWant = ImageFormat.Emf; break;
          case ".EXF" :
          case ".EXIF": imgFmtWant = ImageFormat.Exif; break;
          case ".GIF" : imgFmtWant = ImageFormat.Gif; break;
          case ".ICO" : imgFmtWant = ImageFormat.Icon; break;
          case ".JPG" :
          case ".JPEG": imgFmtWant = ImageFormat.Jpeg; break;
          case ".PNG" : imgFmtWant = ImageFormat.Png; break;
          case ".TIF" :
          case ".TIFF": imgFmtWant = ImageFormat.Tiff; break;
          case ".WMF" : imgFmtWant = ImageFormat.Wmf; break;
          default: // none of the above, so add PNG to the name
              sOutputFilename += ".png";
              this.DoUpdateErrorMsg("WARNING: Output file " + 
                                    "name modified; Extension '.png' added.");
              break;
      }

      bmp.Save(sOutputFilename, imgFmtWant);
      bRet = true;
  }
  catch (Exception ex)
  {
      this.msErrorMsg += this.msEOL + ex.ToString();
      bRet = false;
  }
  return bRet;
}
© . All rights reserved.