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

如何即时创建图像缩略图(图像缩放),包括水印(文本或图像)

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.22/5 (14投票s)

2009年12月12日

CPOL

2分钟阅读

viewsIcon

47161

downloadIcon

1950

本文档描述了如何在运行时调整图像大小并添加水印。

引言

本文档描述了如何在运行时调整图像大小,即您无需存储所有想要在 Web 应用程序中显示的图像尺寸(例如,邮票、中等、大等)。使用此代码,您可以根据需要将图像调整为任何尺寸。您还可以使用文本和另一张图像制作水印。

使用此代码有很多优点,例如:

  • 无需存储不同尺寸的图像,因为您可以将任何图像调整为任何尺寸
  • 易于理解和集成
  • 支持所有浏览器
  • 可用于页面、幻灯片、图像列表、项目列表等。
  • 您可以隐藏图像的路径,因此访问者无法通过在浏览器的地址栏中键入路径来访问它们

Using the Code

要实现调整大小,请按照以下步骤操作:在您的项目中,使用附在本文档中的页面 createthumb_image_WM.aspx。使用 "createthumb_text_WM.aspx" 进行文本水印,使用 "createthumb_image_WM.aspx" 进行图像水印。

只需提供您想要调整大小的文件路径,以及目标宽度和高度,即可调用以下图像调整大小函数

private System.Drawing.Bitmap getResizedImage(string psFilePath, 
        int piTargetWidth, int piTargetHeight)
{
    if (File.Exists(psFilePath))
    {
        original_image = new System.Drawing.Bitmap(psFilePath);

        // Calculate the new width and height
        int width = original_image.Width;
        int height = original_image.Height;
        int target_width = Convert.ToInt32(piTargetWidth);
        int target_height = Convert.ToInt32(piTargetHeight);
        int new_width, new_height;

        if (height <= target_height && width <= target_width)
        {
            new_height = height;
            new_width = width;
        }
        else
        {
            float target_ratio = (float)target_width / (float)target_height;
            float image_ratio = (float)width / (float)height;

            if (target_ratio > image_ratio)
            {
                new_height = target_height;
                new_width = (int)Math.Floor(image_ratio * (float)target_height);
            }
            else
            {
                new_height = (int)Math.Floor((float)target_width / image_ratio);
                new_width = target_width;
            }

            new_width = new_width > target_width ? target_width : new_width;
            new_height = new_height > target_height ? target_height : new_height;
        }

        // Create the thumbnail
        final_image = new System.Drawing.Bitmap(new_width, new_height);
        graphic = System.Drawing.Graphics.FromImage(final_image);
        graphic.FillRectangle(new System.Drawing.SolidBrush(
          System.Drawing.Color.Transparent), 
          new System.Drawing.Rectangle(0, 0, target_width, target_height));
        int paste_x = (target_width - new_width) / 2;
        int paste_y = (target_height - new_height) / 2;
        graphic.InterpolationMode = 
          System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; /* new way */
        graphic.DrawImage(original_image, 0, 0, new_width, new_height);
        if (graphic != null) graphic.Dispose();
        if (original_image != null) original_image.Dispose();
        return final_image;
    }
    else
        return null;
}

例如,如果您想要一个 400x400 的调整大小后的图像,那么您可以像这样使用上述函数:

System.Drawing.Bitmap imgBGImage = getResizedImage(sFilePath, 400, 400);

您将在图像对象 "imgBGImage" 中获得调整大小后的 (400x400) 图像。

现在,让我们看看水印的代码:在以下代码中,根据您的需要更改变量 "sFilePath" 的值

MemoryStream mStream = new MemoryStream();

if (Request.QueryString["_path"] != "")
{
    string sFilePath = "";
    string sWaterMark = "watermark text";
    int x, y;
    
    sFilePath = Server.MapPath("../images/") + Request.QueryString["_path"];

    //resizing the backgroung image
    System.Drawing.Bitmap imgBGImage = getResizedImage(sFilePath, 
      Convert.ToInt32(Request.QueryString["_twidth"]), 
      Convert.ToInt32(Request.QueryString["_theight"]));

    /*drawing water mark text*/
    int startsize = (imgBGImage.Width / sWaterMark.Length);
    //get the font size with respect to length of the string

    //x and y cordinates to draw a string
    x = imgBGImage.Width / 2;
    y = imgBGImage.Height / 2;

    //System.Drawing.StringFormat drawFormat = 
    // new System.Drawing.StringFormat(
    // StringFormatFlags.DirectionVertical); -> draws 
    //          a vertical string for watermark
    System.Drawing.StringFormat drawFormat = 
                new System.Drawing.StringFormat();
    drawFormat.Alignment = StringAlignment.Center;

    drawFormat.FormatFlags = StringFormatFlags.NoWrap;

    //drawing string on Image
    graphic = System.Drawing.Graphics.FromImage(imgBGImage);
    graphic.DrawString(sWaterMark, 
       new Font("Arial", startsize, FontStyle.Regular), 
       new SolidBrush(Color.FromArgb(70, 255, 255, 255)), 
       x, y, drawFormat);
    /*drawing water mark text*/

    //drawing the water mark logo on the backgroung image
    imgBGImage.Save(mStream, System.Drawing.Imaging.ImageFormat.Jpeg);
    Response.Clear();
    Response.ContentType = "image/" + Path.GetExtension(sFilePath);
    Response.BinaryWrite(mStream.GetBuffer());
    if (final_image != null) final_image.Dispose();
    if (imgBGImage != null) imgBGImage.Dispose();
    if (graphic != null) graphic.Dispose();
    if (mStream != null) mStream.Dispose();
    Response.End();

注意:上述代码来自 "createthumb_text_WM.aspx" 页面;请使用 "createthumb_image_WM.aspx" 进行图像水印。

最后,在您想要显示调整大小后的图像的位置使用以下 HTML 代码

它包含以下查询字符串:

  • _path:您想要调整大小的原始图像的名称
  • _twidth:调整大小后的图像的目标宽度
  • _theight:调整大小后的图像的目标高度
<img src="controller/createthumb_text_WM.aspx?_path=test.jpg&_twidth=200&_theight=200" 
  style="border:none;" alt="Loading..."/>
<p>&nbsp;</p>
<img src="controller/createthumb_image_WM.aspx?_path=toyota6.jpg&_twidth=200&_theight=200" 
  style="border:none;" alt="Loading..."/>
<p>&nbsp;</p>
<img src="controller/createthumb_text_WM.aspx?_path=skoda2.jpg&_twidth=200&_theight=200" 
  style="border:none;" alt="Loading..."/>

如上所示,您只需要将页面 URL (controller/createthumb_text_WM.aspx) 传递到图像的 src 属性中,并带有包含高度、宽度和图像名称的查询字符串。您将获得调整大小后的图像!!!

例如,如果您想将图像调整为 200x200,那么为宽度和高度的查询字符串值传递 200,您将获得以下输出

demo_200.JPG

如上例所示,您可以为想要调整到的宽度和高度提供任何值。

此代码也可以与幻灯片一起工作,例如:

demo_slide.JPG

尽情享受轻松的图像调整大小和水印功能吧...... :-)

© . All rights reserved.