根据图片大小c#

时间:2018-10-05 12:35:48

标签: c#

我有一种方案,应该按照图像大小自动分配水印文本大小。我是C#绘图功能的新手。请帮助我解决此问题。

当前逻辑,将固定大小的水印文本应用于图像

protected byte[] WatermarkImage(string PhysicalPath, string Watermarktext)
{

        byte[] imageBytes = null;
        if (File.Exists(PhysicalPath))
        {
            // This is the Name which will appear as a watermark on image.
            string watermark = Watermarktext;

            Image image = Image.FromFile(PhysicalPath);

            Graphics graphic;
            if (image.PixelFormat != PixelFormat.Indexed && image.PixelFormat != PixelFormat.Format8bppIndexed && image.PixelFormat != PixelFormat.Format4bppIndexed && image.PixelFormat != PixelFormat.Format1bppIndexed)
            {

                graphic = Graphics.FromImage(image);
            }
            else
            {

                Bitmap indexedImage = new Bitmap(image);
                graphic = Graphics.FromImage(indexedImage);

                // Draw the contents of the original bitmap onto the new bitmap.
                graphic.DrawImage(image, 0, 0, image.Width, image.Height);
                image = indexedImage;
            }
            graphic.SmoothingMode = SmoothingMode.AntiAlias & SmoothingMode.HighQuality;
            //This is the font for your watermark
            int size = 30; int opacity = 100;
            Font myFont = new Font("Arial", size, FontStyle.Bold, GraphicsUnit.Pixel);
            SolidBrush brush = new SolidBrush(Color.FromArgb(opacity, Color.Beige));

            //This gets the size of the graphic

            SizeF textSize = graphic.MeasureString(watermark, myFont);
            graphic.TranslateTransform(image.Width / 2, image.Height / 2);
            var angle = -45f;
            graphic.RotateTransform(angle);
            var x = -(textSize.Width / 2);
            var y = -(textSize.Height / 2);
            // Code for writing text on the image and showing its postion on images.
            //graphic.RotateTransform(45);
            PointF pointF = new PointF(x, y);

            graphic.DrawString(watermark, myFont, brush, pointF);

            using (MemoryStream memoryStream = new MemoryStream())
            {
                image.Save(memoryStream, GetImageFormat(PhysicalPath));
                imageBytes = memoryStream.ToArray();
            }
        }
        return imageBytes;
}

1 个答案:

答案 0 :(得分:5)

您只需要更改大小值,固定为30,然后将其更改为以下代码即可:

int countOfChar = Watermarktext.Length;
int size = (image.Width + image.Height / 2) / countOfChar;

我对您的代码进行了一些小的测试,并且该代码适用于所有图像尺寸和尺寸。