1

我目前有一个向用户显示的图像,我正在尝试根据传入的两个参数向该图像添加动态文本。

我遇到的问题是,当我单步执行代码时,它似乎一切正常,但是当我在下面的代码运行后在屏幕上看到图像时,它上面没有文本。

以下是我当前的代码设置:

   public ActionResult GenerateImage(string savingAmount, string savingDest)
    {
        // Hardcoding values for testing purposes.
        savingAmount = "25,000.00";
        savingDest = "Canada";


        PointF firstLocation = new PointF(10f, 10f);
        PointF secondLocation = new PointF(10f, 50f);


        Image imgBackground = Image.FromFile(Server.MapPath("~/assets/img/fb-share.jpg"));

        int phWidth = imgBackground.Width; int phHeight = imgBackground.Height;

        Bitmap bmBackground = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);

        bmBackground.SetResolution(72, 72);

        Graphics grBackground = Graphics.FromImage(bmBackground);

        Bitmap bmWatermark;
        Graphics grWatermark;

        bmWatermark = new Bitmap(bmBackground);
        bmWatermark.SetResolution(imgBackground.HorizontalResolution, imgBackground.VerticalResolution);

        grWatermark = Graphics.FromImage(bmWatermark);

        grBackground.SmoothingMode = SmoothingMode.AntiAlias;

        // Now add the dynamic text to image 
        using (Graphics graphics = Graphics.FromImage(imgBackground))
        {
            using (Font arialFont = new Font("Arial", 10))
            {
                grWatermark.DrawString(savingAmount, arialFont, Brushes.White, firstLocation);
                grWatermark.DrawString(savingDest, arialFont, Brushes.White, secondLocation);
            }
        }

        imgBackground.Save(Response.OutputStream, ImageFormat.Png);

        Response.ContentType = "image/png";

        Response.Flush();
        Response.End();


        return null;

    }

正如这段代码运行后提到的那样,我在浏览器中看到了图像,但是图像上没有显示文本,任何人都可以看到/建议可能导致此问题的原因吗?

4

1 回答 1

2

我觉得该代码中有许多图像可以用于您所描述的代码意图。你想要的应该减少到这个:

  1. 加载图像
  2. 在该图像上创建图形
  3. 绘制到图形中并关闭
  4. 向客户端输出图像

在您提供的代码示例中,您在 imgBackground 上打开 Graphics,然后绘制到之前针对您再也不会触摸的图像打开的 grWatermark 图形。

public ActionResult GenerateImage(string savingAmount, string savingDest)
{
    // Hardcoding values for testing purposes.
    savingAmount = "25,000.00";
    savingDest = "Canada";

    PointF firstLocation = new PointF(10f, 10f);
    PointF secondLocation = new PointF(10f, 50f);

    Image imgBackground = Image.FromFile(Server.MapPath("~/assets/img/fb-share.jpg"));
    using (Graphics graphics = Graphics.FromImage(imgBackground))
    {
        using (Font arialFont = new Font("Arial", 10))
        {
            graphics.DrawString(savingAmount, arialFont, Brushes.White, firstLocation);
            graphics.DrawString(savingDest, arialFont, Brushes.White, secondLocation);
        }
    }

    imgBackground.Save(Response.OutputStream, ImageFormat.Png);

    Response.ContentType = "image/png";

    Response.Flush();
    Response.End();

    return null;
}
于 2016-03-17T06:33:26.027 回答