2010-06-23 11:49:00 aiman5818 阅读数 96
  • FFMpeg视频开发与应用基础——使用FFMpeg工具与SDK

    FFMpeg是当今为的面向音视频开发的开源工程,广泛应用于多种音视频的客户端、播放器和流媒体服务器中。使用FFMpeg提供的工具和SDK,可以完成音视频的编码、解码、转码、封装、解封装、转封装、视频水印和视频缩放等多种需求的开发。

    44362 人正在学习 去看看 殷汶杰
ExpandedBlockStart.gif代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Drawing.Imaging;

namespace WaterImage
{
    
public partial class Form2 : Form
    {
        Image imgWeight;

        
public Form2()
        {
            InitializeComponent();
        }
        
/// <summary>
        
/// 从数据库中加载二进制图片
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            
string strSql = "Select Top 1 FileContent From Sys_FileSave";

            Byte[] byteImage 
= new Byte[0];

            byteImage 
= (Byte[])(DbHelperSQL.GetSingle(strSql));

            MemoryStream stmBLOBData 
= new MemoryStream(byteImage);

            imgWeight 
= Image.FromStream(stmBLOBData); pictureBox1.Image = imgWeight;
        }
        
/// <summary>
        
/// 在原图片基础上加载文字水印
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            Graphics GImage 
= Graphics.FromImage(imgWeight);

            addWatermarkText(GImage, 
"重量为60.00吨""WM_BOTTOM_RIGHT", imgWeight.Width, imgWeight.Height);

            pictureBox1.Image 
= imgWeight;
        }
        
/// <summary>
        
/// 在原图片基础上加载图片水印
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            Graphics GImage 
= Graphics.FromImage(imgWeight);

            addWatermarkImage(GImage, 
@"C:\Documents and Settings\Administrator\桌面\Mark.png""WM_TOP_LEFT", imgWeight.Width, imgWeight.Height);

            pictureBox1.Image 
= imgWeight;
        }
        
/// <summary>
        
/// 生成图片缩略图
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            GreateMiniImage(
@"C:\Documents and Settings\Administrator\桌面\Source.jpg"@"C:\Documents and Settings\Administrator\桌面\Small.png"100200);
        }

        
/// <summary>
        
///  加水印文字
        
/// </summary>
        
/// <param name="picture">imge 对象</param>
        
/// <param name="_watermarkText">水印文字内容</param>
        
/// <param name="_watermarkPosition">水印位置</param>
        
/// <param name="_width">被加水印图片的宽</param>
        
/// <param name="_height">被加水印图片的高</param>
        private void addWatermarkText(Graphics picture, string _watermarkText, string _watermarkPosition, int _width, int _height)
        {
            
int[] sizes = new int[] { 16141210864 };
            Font crFont 
= null;
            SizeF crSize 
= new SizeF();
            
for (int i = 0; i < 7; i++)
            {
                crFont 
= new Font("arial", sizes[i], FontStyle.Bold);
                crSize 
= picture.MeasureString(_watermarkText, crFont);

                
if ((ushort)crSize.Width < (ushort)_width)
                    
break;
            }

            
float xpos = 0;
            
float ypos = 0;

            
switch (_watermarkPosition)
            {
                
case "WM_TOP_LEFT":
                    xpos 
= ((float)_width * (float).01+ (crSize.Width / 2);
                    ypos 
= (float)_height * (float).01;
                    
break;
                
case "WM_TOP_RIGHT":
                    xpos 
= ((float)_width * (float).99- (crSize.Width / 2);
                    ypos 
= (float)_height * (float).01;
                    
break;
                
case "WM_BOTTOM_RIGHT":
                    xpos 
= ((float)_width * (float).99- (crSize.Width / 2);
                    ypos 
= ((float)_height * (float).99- crSize.Height;
                    
break;
                
case "WM_BOTTOM_LEFT":
                    xpos 
= ((float)_width * (float).01+ (crSize.Width / 2);
                    ypos 
= ((float)_height * (float).99- crSize.Height;
                    
break;
            }

            StringFormat StrFormat 
= new StringFormat();
            StrFormat.Alignment 
= StringAlignment.Center;

            SolidBrush semiTransBrush2 
= new SolidBrush(Color.FromArgb(153000));
            picture.DrawString(_watermarkText, crFont, semiTransBrush2, xpos 
+ 1, ypos + 1, StrFormat);

            SolidBrush semiTransBrush 
= new SolidBrush(Color.FromArgb(153255255255));
            picture.DrawString(_watermarkText, crFont, semiTransBrush, xpos, ypos, StrFormat);


            semiTransBrush2.Dispose();
            semiTransBrush.Dispose();
        }

        
/// <summary>
        
///  加水印图片
        
/// </summary>
        
/// <param name="picture">imge 对象</param>
        
/// <param name="WaterMarkPicPath">水印图片的地址</param>
        
/// <param name="_watermarkPosition">水印位置</param>
        
/// <param name="_width">被加水印图片的宽</param>
        
/// <param name="_height">被加水印图片的高</param>
        private void addWatermarkImage(Graphics picture, string WaterMarkPicPath, string _watermarkPosition, int _width, int _height)
        {
            Image watermark 
= new Bitmap(WaterMarkPicPath);

            ImageAttributes imageAttributes 
= new ImageAttributes();
            ColorMap colorMap 
= new ColorMap();

            colorMap.OldColor 
= Color.FromArgb(25502550);
            colorMap.NewColor 
= Color.FromArgb(0000);
            ColorMap[] remapTable 
= { colorMap };

            imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

            
float[][] colorMatrixElements = {
                                                
new float[] {1.0f,  0.0f,  0.0f,  0.0f0.0f},
                                                
new float[] {0.0f,  1.0f,  0.0f,  0.0f0.0f},
                                                
new float[] {0.0f,  0.0f,  1.0f,  0.0f0.0f},
                                                
new float[] {0.0f,  0.0f,  0.0f,  0.3f0.0f},
                                                
new float[] {0.0f,  0.0f,  0.0f,  0.0f1.0f}
                                            };

            ColorMatrix colorMatrix 
= new ColorMatrix(colorMatrixElements);

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

            
int xpos = 0;
            
int ypos = 0;
            
int WatermarkWidth = 0;
            
int WatermarkHeight = 0;
            
double bl = 1d;
            
//计算水印图片的比率
            
//取背景的1/4宽度来比较
            if ((_width > watermark.Width * 4&& (_height > watermark.Height * 4))
            {
                bl 
= 1;
            }
            
else if ((_width > watermark.Width * 4&& (_height < watermark.Height * 4))
            {
                bl 
= Convert.ToDouble(_height / 4/ Convert.ToDouble(watermark.Height);

            }
            
else

                
if ((_width < watermark.Width * 4&& (_height > watermark.Height * 4))
                {
                    bl 
= Convert.ToDouble(_width / 4/ Convert.ToDouble(watermark.Width);
                }
                
else
                {
                    
if ((_width * watermark.Height) > (_height * watermark.Width))
                    {
                        bl 
= Convert.ToDouble(_height / 4/ Convert.ToDouble(watermark.Height);

                    }
                    
else
                    {
                        bl 
= Convert.ToDouble(_width / 4/ Convert.ToDouble(watermark.Width);

                    }

                }

            WatermarkWidth 
= Convert.ToInt32(watermark.Width * bl);
            WatermarkHeight 
= Convert.ToInt32(watermark.Height * bl);

            
switch (_watermarkPosition)
            {
                
case "WM_TOP_LEFT":
                    xpos 
= 10;
                    ypos 
= 10;
                    
break;
                
case "WM_TOP_RIGHT":
                    xpos 
= _width - WatermarkWidth - 10;
                    ypos 
= 10;
                    
break;
                
case "WM_BOTTOM_RIGHT":
                    xpos 
= _width - WatermarkWidth - 10;
                    ypos 
= _height - WatermarkHeight - 10;
                    
break;
                
case "WM_BOTTOM_LEFT":
                    xpos 
= 10;
                    ypos 
= _height - WatermarkHeight - 10;
                    
break;
            }

            picture.DrawImage(watermark, 
new Rectangle(xpos, ypos, WatermarkWidth, WatermarkHeight), 00, watermark.Width, watermark.Height, GraphicsUnit.Pixel, imageAttributes);


            watermark.Dispose();
            imageAttributes.Dispose();
        }

        
/// <summary>
        
/// 生成缩略图
        
/// </summary>
        
/// <param name="oldpath">原图片地址</param>
        
/// <param name="newpath">新图片地址</param>
        
/// <param name="tWidth">缩略图的宽</param>
        
/// <param name="tHeight">缩略图的高</param>
        private void GreateMiniImage(string oldpath, string newpath, int tWidth, int tHeight)
        {

            
try
            {

                System.Drawing.Image image 
= System.Drawing.Image.FromFile(oldpath);
                
double bl = 1d;
                
if ((image.Width <= image.Height) && (tWidth >= tHeight))
                {
                    bl 
= Convert.ToDouble(image.Height) / Convert.ToDouble(tHeight);
                }
                
else if ((image.Width > image.Height) && (tWidth < tHeight))
                {
                    bl 
= Convert.ToDouble(image.Width) / Convert.ToDouble(tWidth);

                }
                
else

                    
if ((image.Width <= image.Height) && (tWidth <= tHeight))
                    {
                        
if (image.Height / tHeight >= image.Width / tWidth)
                        {
                            bl 
= Convert.ToDouble(image.Width) / Convert.ToDouble(tWidth);

                        }
                        
else
                        {
                            bl 
= Convert.ToDouble(image.Height) / Convert.ToDouble(tHeight);
                        }
                    }
                    
else
                    {
                        
if (image.Height / tHeight >= image.Width / tWidth)
                        {
                            bl 
= Convert.ToDouble(image.Height) / Convert.ToDouble(tHeight);

                        }
                        
else
                        {
                            bl 
= Convert.ToDouble(image.Width) / Convert.ToDouble(tWidth);

                        }

                    }


                Bitmap b 
= new Bitmap(image, Convert.ToInt32(image.Width / bl), Convert.ToInt32(image.Height / bl));

                b.Save(newpath);
                b.Dispose();
                image.Dispose();


            }
            
catch
            {


            }

        }
    }
}


转载于:https://www.cnblogs.com/zhangpengshou/archive/2010/06/23/1763465.html

2009-04-20 14:12:00 xjxiaohuaa 阅读数 242
  • FFMpeg视频开发与应用基础——使用FFMpeg工具与SDK

    FFMpeg是当今为的面向音视频开发的开源工程,广泛应用于多种音视频的客户端、播放器和流媒体服务器中。使用FFMpeg提供的工具和SDK,可以完成音视频的编码、解码、转码、封装、解封装、转封装、视频水印和视频缩放等多种需求的开发。

    44362 人正在学习 去看看 殷汶杰

using System;
using System.IO;
using System.Collections;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

namespace Imag_writer
{
/// <summary>
/// 水印的类型
/// </summary>
public enum WaterMarkType
{
   /// <summary>
   /// 文字水印
   /// </summary>
   TextMark,
   /// <summary>
   /// 图片水印
   /// </summary>
   //ImageMark // 暂时只能添加文字水印
};

/// <summary>
/// 水印的位置
/// </summary>
public enum WaterMarkPosition
{
   /// <summary>
   /// 左上角
   /// </summary>
   WMP_Left_Top,
   /// <summary>
   /// 左下角
   /// </summary>
   WMP_Left_Bottom,
   /// <summary>
   /// 右上角
   /// </summary>
   WMP_Right_Top,
   /// <summary>
   /// 右下角
   /// </summary>
   WMP_Right_Bottom
};

/// <summary>
/// 处理图片的类(包括加水印,生成缩略图)
/// </summary>
public class ImageWaterMark
{
   public ImageWaterMark()
   {
    //
    // TODO: 在此处添加构造函数逻辑
    //
   }

   #region 给图片加水印
   /// <summary>
   /// 添加水印(分图片水印与文字水印两种)
   /// </summary>
   /// <param name="oldpath">原图片绝对地址</param>
   /// <param name="newpath">新图片放置的绝对地址</param>
   /// <param name="wmtType">要添加的水印的类型</param>
   /// <param name="sWaterMarkContent">水印内容,若添加文字水印,此即为要添加的文字;
   /// 若要添加图片水印,此为图片的路径</param>
   public void addWaterMark(string oldpath, string newpath,
    WaterMarkType wmtType, string sWaterMarkContent)
   {
    try
    {
     Image image = Image.FromFile(oldpath);

     Bitmap b = new Bitmap(image.Width, image.Height,
      PixelFormat.Format24bppRgb);

     Graphics g = Graphics.FromImage(b);
     g.Clear(Color.White);
     g.SmoothingMode = SmoothingMode.HighQuality;
     g.InterpolationMode = InterpolationMode.High;

     g.DrawImage(image, 0, 0, image.Width, image.Height);

     switch (wmtType)
     {
    
      case WaterMarkType.TextMark:
       //文字水印
       this.addWatermarkText(g, sWaterMarkContent, "WM_BOTTOM_RIGHT",
        image.Width, image.Height);
       break;
     }

     b.Save(newpath);
     b.Dispose();
     image.Dispose();
    }
    catch
    {
     if(File.Exists(oldpath))
     {
      File.Delete(oldpath);
     }
    }
    finally
    {
     if(File.Exists(oldpath))
     {
      File.Delete(oldpath);
     }
    } 
   }

   /// <summary>
   ///   加水印文字
   /// </summary>
   /// <param name="picture">imge 对象</param>
   /// <param name="_watermarkText">水印文字内容</param>
   /// <param name="_watermarkPosition">水印位置</param>
   /// <param name="_width">被加水印图片的宽</param>
   /// <param name="_height">被加水印图片的高</param>
   private void addWatermarkText(Graphics picture, string _watermarkText,
    string _watermarkPosition, int _width, int _height)
   {
    // 确定水印文字的字体大小
    int[] sizes = new int[]{32, 30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4};
    Font crFont = null;
    SizeF crSize = new SizeF();
    for (int i = 0;i < sizes.Length; i++)
    {
     crFont = new Font("Arial Black", sizes[i], FontStyle.Bold);
     crSize = picture.MeasureString(_watermarkText, crFont);

     if((ushort)crSize.Width < (ushort)_width)
     {
      break;
     }
    }

    // 生成水印图片(将文字写到图片中)
    Bitmap floatBmp = new Bitmap((int)crSize.Width + 3,
          (int)crSize.Height + 3, PixelFormat.Format32bppArgb);
    Graphics fg=Graphics.FromImage(floatBmp);
    PointF pt=new PointF(0,0);

    // 画阴影文字
    Brush TransparentBrush0 = new SolidBrush(Color.FromArgb(255, Color.Black));
    Brush TransparentBrush1 = new SolidBrush(Color.FromArgb(255, Color.Black));
    fg.DrawString(_watermarkText,crFont,TransparentBrush0, pt.X, pt.Y + 1);
    fg.DrawString(_watermarkText,crFont,TransparentBrush0, pt.X + 1, pt.Y);

    fg.DrawString(_watermarkText,crFont,TransparentBrush1, pt.X + 1, pt.Y + 1);
    fg.DrawString(_watermarkText,crFont,TransparentBrush1, pt.X, pt.Y + 2);
    fg.DrawString(_watermarkText,crFont,TransparentBrush1, pt.X + 2, pt.Y);

    TransparentBrush0.Dispose();
    TransparentBrush1.Dispose();

    // 画文字
    fg.SmoothingMode=System.Drawing.Drawing2D.SmoothingMode.HighQuality;
    fg.DrawString(_watermarkText,
     crFont, new SolidBrush(Color.White),
     pt.X, pt.Y, StringFormat.GenericDefault);

    // 保存刚才的操作
    fg.Save();
    fg.Dispose();
    // floatBmp.Save("d:/WebSite/DIGITALKM/ttt.jpg");

    // 将水印图片加到原图中
    this.addWatermarkImage(
     picture,
     new Bitmap(floatBmp),
     "WM_BOTTOM_RIGHT",
     _width,
     _height);
   }

   /// <summary>
   ///   加水印图片
   /// </summary>
   /// <param name="picture">imge 对象</param>
   /// <param name="iTheImage">Image对象(以此图片为水印)</param>
   /// <param name="_watermarkPosition">水印位置</param>
   /// <param name="_width">被加水印图片的宽</param>
   /// <param name="_height">被加水印图片的高</param>
   private void addWatermarkImage( Graphics picture,Image iTheImage,
    string _watermarkPosition,int _width,int _height)
   {
    Image watermark = new Bitmap(iTheImage);

    ImageAttributes imageAttributes = new ImageAttributes();
    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},
             new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f},
             new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f},
             new float[] {0.0f, 0.0f, 0.0f, 0.3f, 0.0f},
             new float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}
            };

    ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);

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

    int xpos = 0;
    int ypos = 0;
    int WatermarkWidth = 0;
    int WatermarkHeight = 0;
    double bl = 1d;

    //计算水印图片的比率
    //取背景的1/4宽度来比较
    if ((_width > watermark.Width * 4) && (_height > watermark.Height * 4))
    {
     bl = 1;
    }
    else if ((_width > watermark.Width * 4) && (_height<watermark.Height * 4))
    {
     bl = Convert.ToDouble(_height / 4) / Convert.ToDouble(watermark.Height);
           
    }
    else if ((_width < watermark.Width * 4) && (_height > watermark.Height * 4))
    {
     bl = Convert.ToDouble(_width / 4) / Convert.ToDouble(watermark.Width);
    }
    else
    {
     if ((_width * watermark.Height) > (_height * watermark.Width))
     {
      bl = Convert.ToDouble(_height / 4) / Convert.ToDouble(watermark.Height);
                   
     }
     else
     {
      bl = Convert.ToDouble(_width / 4) / Convert.ToDouble(watermark.Width);
                   
     }
           
    }

    WatermarkWidth = Convert.ToInt32(watermark.Width * bl);
    WatermarkHeight = Convert.ToInt32(watermark.Height * bl);

    switch (_watermarkPosition)
    {
     case "WM_TOP_LEFT":
      xpos = 10;
      ypos = 10;
      break;
     case "WM_TOP_RIGHT":
      xpos = _width - WatermarkWidth - 10;
      ypos = 10;
      break;
     case "WM_BOTTOM_RIGHT":
      xpos = _width - WatermarkWidth - 10;
      ypos = _height -WatermarkHeight - 10;
      break;
     case "WM_BOTTOM_LEFT":
      xpos = 10;
      ypos = _height - WatermarkHeight - 10;
      break;
    }

    picture.DrawImage(
     watermark,
     new Rectangle(xpos, ypos, WatermarkWidth, WatermarkHeight),
     0,
     0,
     watermark.Width,
     watermark.Height,
     GraphicsUnit.Pixel,
     imageAttributes);

    watermark.Dispose();
    imageAttributes.Dispose();
   }

   /// <summary>
   ///   加水印图片
   /// </summary>
   /// <param name="picture">imge 对象</param>
   /// <param name="WaterMarkPicPath">水印图片的地址</param>
   /// <param name="_watermarkPosition">水印位置</param>
   /// <param name="_width">被加水印图片的宽</param>
   /// <param name="_height">被加水印图片的高</param>
   private void addWatermarkImage( Graphics picture,string WaterMarkPicPath,
    string _watermarkPosition,int _width,int _height)
   {
    Image watermark = new Bitmap(WaterMarkPicPath);

    this.addWatermarkImage(picture, watermark, _watermarkPosition, _width,
     _height);
   }
   #endregion

   #region 生成缩略图
   /// <summary>
   /// 保存图片
   /// </summary>
   /// <param name="image">Image 对象</param>
   /// <param name="savePath">保存路径</param>
   /// <param name="ici">指定格式的编解码参数</param>
   private void SaveImage(Image image, string savePath, ImageCodecInfo ici)
   {
    //设置 原图片 对象的 EncoderParameters 对象
    EncoderParameters parameters = new EncoderParameters(1);
    parameters.Param[0] = new EncoderParameter(
     System.Drawing.Imaging.Encoder.Quality, ((long) 90));
    image.Save(savePath, ici, parameters);
    parameters.Dispose();
   }

   /// <summary>
   /// 获取图像编码解码器的所有相关信息
   /// </summary>
   /// <param name="mimeType">包含编码解码器的多用途网际邮件扩充协议 (MIME) 类型的字符串</param>
   /// <returns>返回图像编码解码器的所有相关信息</returns>
   private ImageCodecInfo GetCodecInfo(string mimeType)
   {
    ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
    foreach(ImageCodecInfo ici in CodecInfo)
    {
     if(ici.MimeType == mimeType)
      return ici;
    }
    return null;
   }

   /// <summary>
   /// 生成缩略图
   /// </summary>
   /// <param name="sourceImagePath">原图片路径(相对路径)</param>
   /// <param name="thumbnailImagePath">生成的缩略图路径,如果为空则保存为原图片路径(相对路径)</param>
   /// <param name="thumbnailImageWidth">缩略图的宽度(高度与按源图片比例自动生成)</param>
   public void ToThumbnailImages(
    string SourceImagePath,
    string ThumbnailImagePath,
    int ThumbnailImageWidth)
   {
    Hashtable htmimes = new Hashtable();
    htmimes[".jpeg"] = "image/jpeg";
    htmimes[".jpg"] = "image/jpeg";  
    htmimes[".png"] = "image/png";  
    htmimes[".tif"] = "image/tiff";
    htmimes[".tiff"] = "image/tiff";
    htmimes[".bmp"] = "image/bmp";
    htmimes[".gif"] = "image/gif";

    // 取得原图片的后缀
    string sExt = SourceImagePath.Substring(
     SourceImagePath.LastIndexOf(".")).ToLower();

    //从 原图片创建 Image 对象
    Image image = Image.FromFile(SourceImagePath); 
    int num = ((ThumbnailImageWidth / 4) * 3);
    int width = image.Width;
    int height = image.Height;

    //计算图片的比例
    if ((((double) width) / ((double) height)) >= 1.3333333333333333f)
    {
     num = ((height * ThumbnailImageWidth) / width);
    }
    else
    {
     ThumbnailImageWidth = ((width * num) / height);
    }
    if ((ThumbnailImageWidth < 1) || (num < 1))
    {
     return;
    }

    //用指定的大小和格式初始化 Bitmap 类的新实例
    Bitmap bitmap = new Bitmap(ThumbnailImageWidth, num,
     PixelFormat.Format32bppArgb);

    //从指定的 Image 对象创建新 Graphics 对象
    Graphics graphics = Graphics.FromImage(bitmap);

    //清除整个绘图面并以透明背景色填充
    graphics.Clear(Color.Transparent);

    graphics.SmoothingMode = SmoothingMode.HighQuality;
    graphics.InterpolationMode = InterpolationMode.High;

    //在指定位置并且按指定大小绘制 原图片 对象
    graphics.DrawImage(image, new Rectangle(0, 0, ThumbnailImageWidth, num));
    image.Dispose();
  
    try
    {  
     //将此 原图片 以指定格式并用指定的编解码参数保存到指定文件
     SaveImage(bitmap, ThumbnailImagePath,
      GetCodecInfo((string)htmimes[sExt]));
    }
    catch(System.Exception e)
    {
     throw e;
    }
   }
   #endregion
}
}

来源:http://www.52dotnet.net/CSharp/270.html

2015-07-15 14:50:54 threadroc 阅读数 972
  • FFMpeg视频开发与应用基础——使用FFMpeg工具与SDK

    FFMpeg是当今为的面向音视频开发的开源工程,广泛应用于多种音视频的客户端、播放器和流媒体服务器中。使用FFMpeg提供的工具和SDK,可以完成音视频的编码、解码、转码、封装、解封装、转封装、视频水印和视频缩放等多种需求的开发。

    44362 人正在学习 去看看 殷汶杰

using System;   

using System.Drawing;   

using System.Drawing.Imaging;   

using System.Drawing.Drawing2D;   

using System.IO;   

/// <summary>   

/// 图片位置   

/// </summary>   

public enum ImagePosition   

{   

    LeftTop,        //左上   

    LeftBottom,    //左下   

    RightTop,       //右上   

    RigthBottom,  //右下   

    TopMiddle,     //顶部居中   

    BottomMiddle, //底部居中   

    Center           //中心   

}   

   

/// <summary>   

/// 水印图片的操作管理 Design by Gary Gong From Demetersoft.com   

/// </summary>   

public class WaterImageManage   

{   

    /// <summary>   

    /// 生成一个新的水印图片制作实例   

    /// </summary>   

    public WaterImageManage ()   

    {   

        //   

        // TODO: Add constructor logic here   

        //   

    }   

   

    /// <summary>   

    /// 添加图片水印   

    /// </summary>   

    /// <param name="sourcePicture">源图片文件名</param>   

    /// <param name="waterImage">水印图片文件名</param>   

    /// <param name="alpha">透明度(0.1-1.0数值越小透明度越高)</param>   

    /// <param name="position">位置</param>   

    /// <param name="PicturePath" >图片的路径</param>   

    /// <returns>返回生成于指定文件夹下的水印文件名</returns>   

    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,"");   

    }   

   

    /// <summary>   

    /// 在图片上添加水印文字   

    /// </summary>   

    /// <param name="sourcePicture">源图片文件</param>   

    /// <param name="waterWords">需要添加到图片上的文字</param>   

    /// <param name="alpha">透明度</param>   

    /// <param name="position">位置</param>   

    /// <param name="PicturePath">文件路径</param>   

    /// <returns></returns>   

    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;   

        }   

   

        //   

        // 源图片全路径   

        //   

        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, "");   

    }   

}   

   

/// <summary>   

/// 装载水印图片的相关信息   

/// </summary>   

public class WaterImage   

{   

    public WaterImage ()   

    {   

   

    }   

   

    private string m_sourcePicture;   

    /// <summary>   

    /// 源图片地址名字(带后缀)   

    /// </summary>   

    public string SourcePicture   

    {   

        get { return m_sourcePicture; }   

        set { m_sourcePicture = value; }   

    }   

   

    private string  m_waterImager;   

    /// <summary>   

    /// 水印图片名字(带后缀)   

    /// </summary>   

    public string  WaterPicture   

    {   

        get { return m_waterImager; }   

        set { m_waterImager = value; }   

    }   

   

    private float  m_alpha;   

    /// <summary>   

    /// 水印图片文字的透明度   

    /// </summary>   

    public float  Alpha   

    {   

        get { return m_alpha; }   

        set { m_alpha = value; }   

    }   

   

    private ImagePosition  m_postition;   

    /// <summary>   

    /// 水印图片或文字在图片中的位置   

    /// </summary>   

    public ImagePosition  Position   

    {   

        get { return m_postition; }   

        set { m_postition = value; }   

    }   

   

    private string  m_words;   

    /// <summary>   

    /// 水印文字的内容   

    /// </summary>   

    public string  Words   

    {   

        get { return m_words; }   

        set { m_words = value; }   

    }   

        

 

2009-05-18 12:08:00 liuhelong 阅读数 1749
  • FFMpeg视频开发与应用基础——使用FFMpeg工具与SDK

    FFMpeg是当今为的面向音视频开发的开源工程,广泛应用于多种音视频的客户端、播放器和流媒体服务器中。使用FFMpeg提供的工具和SDK,可以完成音视频的编码、解码、转码、封装、解封装、转封装、视频水印和视频缩放等多种需求的开发。

    44362 人正在学习 去看看 殷汶杰

图片加水印的方法有很多,这里先对临时加水印的方法进行下介绍

临时加水印:

就是在响应用户请求时对响应中的图片在内在中加水印,然后写入输出流,传到客户端。

这样就能实现在不改变原图的情况下,呈现给客户水印图片

 

首先我们需要定义一个实现IHttpHandler 接口的类:

 

 

然后在配置文件中引用这个处理类/并配置水印图片位置:

 

完成。

这样在页面被访问的时候,path目录下的图片会被自动加上水印

2018-08-23 10:09:59 qq_37385726 阅读数 1689
  • FFMpeg视频开发与应用基础——使用FFMpeg工具与SDK

    FFMpeg是当今为的面向音视频开发的开源工程,广泛应用于多种音视频的客户端、播放器和流媒体服务器中。使用FFMpeg提供的工具和SDK,可以完成音视频的编码、解码、转码、封装、解封装、转封装、视频水印和视频缩放等多种需求的开发。

    44362 人正在学习 去看看 殷汶杰

目录

一、水印为英文

二、水印为中文


一、水印为英文

直接使用cv2中的putText

import cv2

img1 = cv2.imread('./Image/reba_color.jpg',cv2.IMREAD_COLOR)

text = 'Python Opencv'
pos = (10,150)
font_type = 4
font_size = 2
color = (255,255,255)
bold = 1

#图片,文字,位置,字体,字号,颜色,厚度
cv2.putText(img1,text,pos, font_type, font_size, color,bold)
cv2.imshow('img',img1)
cv2.waitKey(0)

 

二、水印为中文

这种情况下处理较为复杂,因为cv2的putText直接输出中文会出现乱码的情况。

一般有两种解决办法:

  • freetype模块,但这种方法及其麻烦,完全不建议尝试
  • 利用PIL对象和opencv对象进行数据类型转换实现

opencv对象转PIL对象,注意将opencv的BGR通道转成RGB通道

Image.fromarray(cv2.cvtColor(img1, cv2.COLOR_BGR2RGB))

PIL对象转opencv对象,注意将PIL的RGB通道转成BGR通道

cv_img = cv2.cvtColor(np.asarray(pil_image),cv2.COLOR_RGB2BGR)

 

import cv2
from PIL import Image,ImageFont,ImageDraw
import numpy as np

img1 = cv2.imread('./Image/reba_color.jpg',cv2.IMREAD_COLOR)

pil_image = Image.fromarray(cv2.cvtColor(img1, cv2.COLOR_BGR2RGB))

font = ImageFont.truetype('sarasa-mono-sc-regular.ttf', 40)
color = (255,255,255)
pos = (10,150)
text = u"我是水印"

draw = ImageDraw.Draw(pil_image)
draw.text(pos,text,font=font,fill=color)

cv_img = cv2.cvtColor(np.asarray(pil_image),cv2.COLOR_RGB2BGR)

cv2.imshow('imgg',cv_img)

cv2.waitKey(0)

c# 图片加水印

阅读数 5

没有更多推荐了,返回首页