C#(.net)透かし画像の生成完全インスタンス

17611 ワード

本稿では,C#透かし画像の生成方法を完全な例で述べた.とても実用的なテクニックです.皆さんの参考にしてください.
具体的なインスタンスコードは次のとおりです.

/*
* 
*      :
*         WaterImage  
*           ,            
*        WaterImageManage  
*    WaterImageManage    DrawImage(),     
*  DrawWords()     
* 
*/
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.IO;

namespace ABC
{

  /// 
  ///     
  /// 
  public enum ImagePosition
  {
    LeftTop,    //  
    LeftBottom,  //  
    RightTop,    //  
    RigthBottom, //  
    TopMiddle,   //    
    BottomMiddle, //    
    Center      //  
  }

  /// 
  ///           Design by Gary Gong From Demetersoft.com
  /// 
  public class WaterImageManage
  {
    /// 
    ///               
    /// 
    public WaterImageManage()
    {
      //
      // TODO: Add constructor logic here
      //
    }

    /// 
    ///       
    /// 
    ///       
    ///        
    ///    (0.1-1.0         )
    ///   
    ///      
    ///                  
    public string DrawImage(string sourcePicture,
                     string waterImage,
                     float alpha,

                     ImagePosition position,
                     string PicturePath)
    {
      //
      //         
      //
      if (sourcePicture == string.Empty || waterImage == string.Empty || alpha == 0.0 || PicturePath == string.Empty)
      {
        return sourcePicture;
      }

      //
      //    ,       
      //
      string sourcePictureName = PicturePath + sourcePicture;
      string waterPictureName = PicturePath + waterImage;
      string fileSourceExtension = System.IO.Path.GetExtension(sourcePictureName).ToLower();
      string fileWaterExtension = System.IO.Path.GetExtension(waterPictureName).ToLower();
      //
      //         ,        
      //
      if (System.IO.File.Exists(sourcePictureName) == false ||
        System.IO.File.Exists(waterPictureName) == false || (
        fileSourceExtension != ".gif" &&
        fileSourceExtension != ".jpg" &&
        fileSourceExtension != ".png") || (
        fileWaterExtension != ".gif" &&
        fileWaterExtension != ".jpg" &&
        fileWaterExtension != ".png")
        )
      {
        return sourcePicture;
      }

      //

      //           
      //
      string targetImage = sourcePictureName.Replace(System.IO.Path.GetExtension(sourcePictureName), "") + "_1101.jpg";

      //
      //              Image   
      //
      Image imgPhoto = Image.FromFile(sourcePictureName);
      //
      //      
      //
      int phWidth = imgPhoto.Width;
      int phHeight = imgPhoto.Height;

      //
      //    GDI+   ,                   。
      //
      Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);

      //
      //      
      // 
      bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

      //
      //               
      //
      Graphics grPhoto = Graphics.FromImage(bmPhoto);

      //
      //  ,       ,         Image    
      //
      Image imgWatermark = new Bitmap(waterPictureName);

      //
      //             
      //
      int wmWidth = imgWatermark.Width;
      int wmHeight = imgWatermark.Height;

      //SmoothingMode:         (    )     、           。
      //          
      // AntiAlias            。 
      // Default           。

      // HighQuality      、     。 
      // HighSpeed       、     。 
      // Invalid            。 
      // None            。 
      grPhoto.SmoothingMode = SmoothingMode.AntiAlias;

 

      //
      //      ,              
      //
      grPhoto.DrawImage(imgPhoto,
                    new Rectangle(0, 0, phWidth, phHeight),
                    0,
                    0,
                    phWidth,
                    phHeight,
                    GraphicsUnit.Pixel);

      //
      //      ,               。       
      //
      Bitmap bmWatermark = new Bitmap(bmPhoto);
      bmWatermark.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

      //
      //   ,              grWatermark
      //
      Graphics grWatermark = Graphics.FromImage(bmWatermark);

      //
      //ImageAttributes                           。
      //   

      ImageAttributes imageAttributes = new ImageAttributes();

      //
      //Colormap:          
      //
      ColorMap colorMap = new ColorMap();

      //
      //                         
      //
      colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
      colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);

      ColorMap[] remapTable = { colorMap };

      imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

      float[][] colorMatrixElements = { 
      new float[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // red  
      new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f}, //green  
      new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f}, //blue      
      new float[] {0.0f, 0.0f, 0.0f, alpha, 0.0f}, //      
      new float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}};//

      // ColorMatrix:     RGBA       5 x 5   。
      // ImageAttributes                     。
      ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);


      imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default,
       ColorAdjustType.Bitmap);

      //
      //       ,        
      //
      int xPosOfWm;
      int yPosOfWm;

      switch (position)
      {
        case ImagePosition.BottomMiddle:
          xPosOfWm = (phWidth - wmWidth) / 2;
          yPosOfWm = phHeight - wmHeight - 10;
          break;

        case ImagePosition.Center:
          xPosOfWm = (phWidth - wmWidth) / 2;
          yPosOfWm = (phHeight - wmHeight) / 2;
          break;
        case ImagePosition.LeftBottom:
          xPosOfWm = 10;
          yPosOfWm = phHeight - wmHeight - 10;
          break;
        case ImagePosition.LeftTop:
          xPosOfWm = 10;
          yPosOfWm = 10;
          break;
        case ImagePosition.RightTop:
          xPosOfWm = phWidth - wmWidth - 10;
          yPosOfWm = 10;
          break;
        case ImagePosition.RigthBottom:
          xPosOfWm = phWidth - wmWidth - 10;
          yPosOfWm = phHeight - wmHeight - 10;
          break;
        case ImagePosition.TopMiddle:
          xPosOfWm = (phWidth - wmWidth) / 2;
          yPosOfWm = 10;
          break;
        default:
          xPosOfWm = 10;
          yPosOfWm = phHeight - wmHeight - 10;
          break;
      }

      //      ,      
      //
      grWatermark.DrawImage(imgWatermark,
       new Rectangle(xPosOfWm,
                 yPosOfWm,
                 wmWidth,
                 wmHeight),
                 0,
                 0,
                 wmWidth,
                 wmHeight,
                 GraphicsUnit.Pixel,
                 imageAttributes);

      imgPhoto = bmWatermark;
      grPhoto.Dispose();
      grWatermark.Dispose();

      //
      //               
      //
      imgPhoto.Save(targetImage, ImageFormat.Jpeg);
      imgPhoto.Dispose();
      imgWatermark.Dispose();
      return targetImage.Replace(PicturePath, "");
    }

/*
* 
*     :
*         WaterImage  
*           ,            
*        WaterImageManage  
*    WaterImageManage    DrawImage(),     
*  DrawWords()     
* 
-*/

    /// 
    ///           
    /// 
    ///      (   ,     )

    ///            
    ///    
    ///   
    ///     
    /// 
    public string DrawWords(string sourcePicture,
                     string waterWords,
                     float alpha,
                     ImagePosition position,
                     string PicturePath)
    {
      //
      //         
      //
      if (sourcePicture == string.Empty || waterWords == string.Empty || alpha == 0.0 || PicturePath == string.Empty)
      {
        return sourcePicture;
      }

      //
      //       
      //
      if (PicturePath.Substring(PicturePath.Length - 1, 1) != "/")
        PicturePath += "/";
      string sourcePictureName = PicturePath + sourcePicture;
      string fileExtension = System.IO.Path.GetExtension(sourcePictureName).ToLower();

      //
      //         ,         
      //
      if (System.IO.File.Exists(sourcePictureName) == false || (
        fileExtension != ".gif" &&
        fileExtension != ".jpg" &&

        fileExtension != ".png"))
      {
        return sourcePicture;
      }

      //
      //           
      //
      string targetImage = sourcePictureName.Replace(System.IO.Path.GetExtension(sourcePictureName), "") + "_0703.jpg";

      //                     
      Image imgPhoto = Image.FromFile(sourcePictureName);

      //        
      int phWidth = imgPhoto.Width;
      int phHeight = imgPhoto.Height;

      //
      //    bitmap,               
      Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);

      //SetResolution:    Bitmap     
      //                       bitmap
      bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

      //Graphics:     GDI+     。
      Graphics grPhoto = Graphics.FromImage(bmPhoto);

      //       
      grPhoto.SmoothingMode = SmoothingMode.AntiAlias;

      //                   (  )    
      grPhoto.DrawImage(
       imgPhoto,                      //          
       new Rectangle(0, 0, phWidth, phHeight), //               
       0,                           // X   0     
       0,                           // Y  

       phWidth,                      // X      
       phHeight,                      // Y      
       GraphicsUnit.Pixel);               //      ,       

      //                      
      //              
      int[] sizes = new int[] { 16, 14, 12, 10, 8, 6, 4 };

      //  
      Font crFont = null;
      //        ,SizeF     ,   Height ,width ,IsEmpty    
      SizeF crSize = new SizeF();

      //                     
      //             
      for (int i = 0; i < 7; i++)
      {
        crFont = new Font("arial", sizes[i], FontStyle.Bold);

        //       Font           StringFormat            。
        crSize = grPhoto.MeasureString(waterWords, crFont);

        // ushort              
        if ((ushort)crSize.Width < (ushort)phWidth)
          break;
      }

      //  5%   ,      (               ,        )
      int yPixlesFromBottom = (int)(phHeight * .05);

      //           
      float wmHeight = crSize.Height;
      float wmWidth = crSize.Width;

      float xPosOfWm;

      float yPosOfWm;

   switch (position)
      {
        case ImagePosition.BottomMiddle:
          xPosOfWm = phWidth / 2;
          yPosOfWm = phHeight - wmHeight - 10;
          break;
        case ImagePosition.Center:
          xPosOfWm = phWidth / 2;
          yPosOfWm = phHeight / 2;
          break;
        case ImagePosition.LeftBottom:
          xPosOfWm = wmWidth;
          yPosOfWm = phHeight - wmHeight - 10;
          break;
        case ImagePosition.LeftTop:
          xPosOfWm = wmWidth / 2;
          yPosOfWm = wmHeight / 2;
          break;
        case ImagePosition.RightTop:
          xPosOfWm = phWidth - wmWidth - 10;
          yPosOfWm = wmHeight;
          break;
        case ImagePosition.RigthBottom:
          xPosOfWm = phWidth - wmWidth - 10;
          yPosOfWm = phHeight - wmHeight - 10;
          break;
        case ImagePosition.TopMiddle:
          xPosOfWm = phWidth / 2;
          yPosOfWm = wmWidth;

          break;
        default:
          xPosOfWm = wmWidth;
          yPosOfWm = phHeight - wmHeight - 10;
          break;
      }

      //        (   、      Tab    ),    (            (National)     )  OpenType   。
      StringFormat StrFormat = new StringFormat();

      //            
      StrFormat.Alignment = StringAlignment.Center;

      //SolidBrush:      。          ,   、  、  、        。
      //            ,   
      int m_alpha = Convert.ToInt32(256 * alpha);
      SolidBrush semiTransBrush2 = new SolidBrush(Color.FromArgb(m_alpha, 0, 0, 0));

      //      ,               ,      
      //DrawString             Brush   Font             。
      grPhoto.DrawString(waterWords,                  //string of text
                    crFont,                     //font
                    semiTransBrush2,              //Brush
                    new PointF(xPosOfWm + 1, yPosOfWm + 1), //Position
                    StrFormat);

      //    ARGB   (alpha、  、     )    Color   ,        153
      //              ,   
      SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(153, 255, 255, 255));

      //         ,            
      grPhoto.DrawString(waterWords,         //string of text
                    crFont,                  //font
                    semiTransBrush,              //Brush
                    new PointF(xPosOfWm, yPosOfWm), //Position
                    StrFormat);

      //imgPhoto               Image  
      //bmPhoto            , Bitmap  
      imgPhoto = bmPhoto;
      //    ,    Graphics  grPhoto  ,grPhoto    
      grPhoto.Dispose();

      // grPhoto  
      imgPhoto.Save(targetImage, ImageFormat.Jpeg);
      imgPhoto.Dispose();

      return targetImage.Replace(PicturePath, "");
    }
  }

  /// 
  ///            
  /// 
  public class WaterImage
  {
    public WaterImage()
    {

    }

    private string m_sourcePicture;
    /// 
    ///        (   )

    /// 
    public string SourcePicture
    {
      get { return m_sourcePicture; }
      set { m_sourcePicture = value; }
    }

    private string m_waterImager;
    /// 
    ///       (   )
    /// 
    public string WaterPicture
    {
      get { return m_waterImager; }
      set { m_waterImager = value; }
    }

    private float m_alpha;
    /// 
    ///           
    /// 
    public float Alpha
    {
      get { return m_alpha; }
      set { m_alpha = value; }
    }

    private ImagePosition m_postition;
    /// 
    ///               
    /// 
    public ImagePosition Position
    {
      get { return m_postition; }
      set { m_postition = value; }
    }

    private string m_words;
    /// 
    ///        
    /// 
    public string Words
    {
      get { return m_words; }
      set { m_words = value; }
    }

  }
}

本文で述べたことは皆さんのC#プログラム設計に参考になると信じています.