C# 图片添加文字水印优化:解决内存不足问题

该 C# 方法用于给图片添加自定义文字水印,但偶尔会遇到内存不足的问题。以下是优化方案:

原始代码:

public static Stream GetImageTextWaterMask(Stream sourceImageStream, string text)
{
    Stream result = null;
    Image sourceImage = Image.FromStream(sourceImageStream);
    using (Image maskImage = GenTextImage(text, StringFormatFlags.DisplayFormatControl))
    {
        int xPoint;
        int yPoint;
        if (sourceImage.Width >= maskImage.Width)
        {
            xPoint = (sourceImage.Width - maskImage.Width) - 2;
            yPoint = (sourceImage.Height - maskImage.Height) - 2;
            return ImageHelper.GetImageWaterMask(sourceImage, maskImage, xPoint, yPoint, ImageFormat.Jpeg, 0x55L, 100f, Color.Transparent);
        }
        using (Image maskImage2 = GenTextImage(text, StringFormatFlags.DirectionVertical))
        {
            xPoint = (sourceImage.Width - maskImage2.Width) - 2;
            yPoint = (sourceImage.Height - maskImage2.Height) - 2;
            result = ImageHelper.GetImageWaterMask(sourceImage, maskImage2, xPoint, yPoint, ImageFormat.Jpeg, 0x55L, 100f, Color.Transparent);
        }
    }
    return result;
}

优化后的代码:

  1. 使用 using 语句释放资源:

  2. 使用 Bitmap 代替 Image

  3. 避免重复生成水印图像:

public static Stream GetImageTextWaterMask(Stream sourceImageStream, string text)
{
    Stream result = null;
    using (Image sourceImage = Image.FromStream(sourceImageStream))
    {
        using (Bitmap maskImage = GenTextBitmap(text, StringFormatFlags.DisplayFormatControl))
        {
            int xPoint;
            int yPoint;
            if (sourceImage.Width >= maskImage.Width)
            {
                xPoint = (sourceImage.Width - maskImage.Width) - 2;
                yPoint = (sourceImage.Height - maskImage.Height) - 2;
                return ImageHelper.GetImageWaterMask(sourceImage, maskImage, xPoint, yPoint, ImageFormat.Jpeg, 0x55L, 100f, Color.Transparent);
            }
            using (Bitmap maskImage2 = GenTextBitmap(text, StringFormatFlags.DirectionVertical))
            {
                xPoint = (sourceImage.Width - maskImage2.Width) - 2;
                yPoint = (sourceImage.Height - maskImage2.Height) - 2;
                result = ImageHelper.GetImageWaterMask(sourceImage, maskImage2, xPoint, yPoint, ImageFormat.Jpeg, 0x55L, 100f, Color.Transparent);
            }
        }
    }
    return result;
}

private static Bitmap GenTextBitmap(string text, StringFormatFlags formatFlags)
{
    Bitmap bitmap = new Bitmap(1, 1);
    using (Graphics graphics = Graphics.FromImage(bitmap))
    {
        SizeF sizeF = graphics.MeasureString(text, new Font('宋体', 20));
        bitmap = new Bitmap((int)sizeF.Width, (int)sizeF.Height);
        graphics.DrawString(text, new Font('宋体', 20), Brushes.White, new RectangleF(0, 0, sizeF.Width, sizeF.Height), new StringFormat(formatFlags));
    }
    return bitmap;
}

通过这些优化措施,可以有效减少内存占用,提高代码效率。

C# 图片添加文字水印优化:解决内存不足问题

原文地址: https://www.cveoy.top/t/topic/lq1Q 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录