C# 图片水印方法优化 - 减少内存占用
public static Stream GetImageTextWaterMask(Stream sourceImageStream, string text)
{
Stream result = null;
using (Image sourceImage = Image.FromStream(sourceImageStream))
{
using (Bitmap 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 (Bitmap 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;
}
这是一个由C#编写的方法,其目的是为了给图片打上自定义文字水印,偶尔会遇到内存不足的问题,下面提供一些优化方法:
-
使用using语句释放资源:代码已使用using语句释放Image和Bitmap对象,确保及时释放资源,避免内存泄漏。
-
使用Bitmap对象替代Image对象:代码已使用Bitmap对象替代Image对象,Bitmap对象比Image对象更适合处理图像,因为它具有更高效的像素访问方式和更好的内存管理。
-
使用缩略图:若处理大尺寸图像,可以考虑使用缩略图来减少内存占用,同时不影响水印的质量。可以使用
Image.GetThumbnailImage()方法生成缩略图。 -
减少创建新对象的次数:代码中已尽量减少创建新对象的次数,仅在需要时才创建Bitmap对象。
-
使用合适的格式:代码已使用JPEG格式,JPEG格式可以保持水印质量的同时减少文件大小和内存占用。
补充说明
GenTextImage方法需要根据具体实现进行优化,例如可以考虑使用更轻量的绘图方法。ImageHelper.GetImageWaterMask方法也需要确保资源的及时释放。- 若内存问题依然存在,可以考虑使用其他技术,例如使用Graphics类直接在原图上绘制水印,或者使用第三方库进行图像处理。
通过以上优化,可以有效减少图片水印方法的内存占用,提高程序性能。
原文地址: https://www.cveoy.top/t/topic/lq1K 著作权归作者所有。请勿转载和采集!