簡體   English   中英

根據圖像大小c#動態分配水印文本大小

[英]Dynamically assign watermark text size based on image size 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;
}

你只需要更改你的大小值,30是固定的,並將其更改為以下代碼:

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

我測試了您的代碼,稍作修改,適用於所有圖像尺寸和尺寸。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM