在高质量的图像上设置水印

本文关键字:设置 图像 高质量 | 更新日期: 2023-09-27 18:20:23

我有一个在图像上设置水印的处理程序。问题是质量不太好。这是代码:

    byte[] imageBytes = null;
    using (Graphics G = Graphics.FromImage(ImageToWatermark))
    {
        using (ImageAttributes IA = new ImageAttributes())
        {
            ColorMatrix CM = new ColorMatrix();
            CM.Matrix33 = Opacity;
            IA.SetColorMatrix(CM);
            G.DrawImage(Watermark, new Rectangle(WatermarkPosition, Watermark.Size), 0, 0, Watermark.Width, Watermark.Height, GraphicsUnit.Pixel, IA);
        }
    }
    using (MemoryStream memoryStream = new MemoryStream())
    {
        ImageToWatermark.Save(memoryStream, GetImageFormat(context.Request.PhysicalPath));
        imageBytes = memoryStream.ToArray();
    }

如何设置结果的质量?

在高质量的图像上设置水印

如果您的图像格式是Jpeg,那么您可以使用以下示例方法手动设置输出质量以保存到磁盘:

    public void SaveJpg(string path, Bitmap img, long quality) {
        // Encoder parameter for image quality
        EncoderParameter qualityParam = new EncoderParameter(Encoder.Quality, quality);
        // Jpeg image codec
        ImageCodecInfo jpegCodec = this.getEncoderInfo("image/jpeg");
        EncoderParameters encoderParams = new EncoderParameters(1);
        encoderParams.Param[0] = qualityParam;
        img.Save(path, jpegCodec, encoderParams);
    }

或者,在您的情况下,使用以下代码:

using (MemoryStream memoryStream = new MemoryStream())
    {
        EncoderParameter qualityParam = new EncoderParameter(Encoder.Quality, 80); // edit image quality here
        ImageCodecInfo jpegCodec = this.getEncoderInfo("image/jpeg");
        EncoderParameters encoderParams = new EncoderParameters(1);
        encoderParams.Param[0] = qualityParam;
        ImageToWatermark.Save(memoryStream, encoderParams);
        imageBytes = memoryStream.ToArray();
    }

一般来说,60到100的质量应该产生足够好的Jpeg图像用于屏幕输出。