0

我正在为自己和工作中的其他人制作批处理水印工具,使用以下代码可以注释图像右下角的文本,但如果不手动调整,我无法让它在左下角进行注释任何给定图像的不同坐标。将 StringAlignment.Far 更改为 StringAlignment.Near 等也不会做任何事情,但可能会在图像之外的某个不显示的地方注释文本。

MSDN 有一些解释,但对我没有帮助。任何帮助都会很棒我已经为此奋斗了一段时间。

private void button1_Click(object sender, EventArgs e)
{
    foreach (string images in Directory.GetFiles(textBox1.Text))
    {
        System.Drawing.Image img = System.Drawing.Image.FromFile(images);

        Graphics gr = Graphics.FromImage(img);

        Font font = new Font("Times New Roman", (float)25, 
            System.Drawing.FontStyle.Regular);
        System.Drawing.Color color = System.Drawing.Color.Red;

        StringFormat stringFormat = new StringFormat();
        stringFormat.Alignment = StringAlignment.Far;
        stringFormat.LineAlignment = StringAlignment.Far;

        gr.SmoothingMode = SmoothingMode.AntiAlias;

        gr.DrawString("WATERMARK GOES HERE"+ images, font, 
            new System.Drawing.SolidBrush(color), 
            new System.Drawing.Point(img.Width - 0, img.Height - 0), 
            stringFormat);

        MemoryStream outputStream = new MemoryStream();
        img.Save(images+"Stamped.jpg");
    }

    MessageBox.Show("done");
}
4

1 回答 1

4
  • 命名您的控件。不要使用“button1”、“textbox1”等。
  • 使用“使用”语句。编写“System.Drawing.Point”和其他完全限定的名称只会增加代码的大小并使其更难阅读。
  • 您正在为要添加水印的每个图像创建一个 SolidBrush 类的新实例。您应该在循环之前创建画笔并在循环中使用它,然后再将其丢弃。
  • 您对 MemoryStream 的声明什么都不做,也无处使用。

至于水印本身,您应该决定是否希望它与图像大小一起缩放,或者保持一致的大小。或者你可以让它有一个最大/最小尺寸。那是你的偏好。

private void watermark_btn_Click(object sender, EventArgs e)
{
    string watermarkText = "ShowThisWatermark";

    using (Font font = new Font("Times New Roman", (float)25, FontStyle.Regular))
    using (SolidBrush brush = new SolidBrush(Color.Red))
    foreach (string file in Directory.GetFiles(directory_txt.Text))
    {
        try
        {
            Bitmap b = new Bitmap(file);

            using (Graphics g = Graphics.FromImage(b))
            {
                g.SmoothingMode = SmoothingMode.AntiAlias;

                SizeF measuredSize = g.MeasureString(watermarkText, font);

                // Use this to watermark the bottom-left corner
                g.DrawString(watermarkText, font, brush, 0, b.Height - measuredSize.Height);

                // Use this to watermark the bottom-right corner
                g.DrawString(watermarkText, font, brush, b.Width - measuredSize.Width, b.Height - measuredSize.Height);
            }

            b.Save(Path.GetFileNameWithoutExtension(file) + "_stamped" + Path.GetExtension(file));
        }
        catch
        {
            continue;
        }
    }
}

The try/catch is a lazy way of skipping files which aren't images. Since Directory.GetFiles returns all files in the directory, a non-image file would cause an exception. This could be done in a much neater fashion, but since that was not the nature of your question I kept it simple.

于 2011-12-29T06:15:51.143 回答