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

时间:2012-01-13 10:36:23

标签: c# asp.net

我有一个处理器,它在图像上设置了水印。问题是质量不太好。 这是代码:

    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();
    }

如何设置结果的质量?

谢谢你, 阿丽娜

1 个答案:

答案 0 :(得分:1)

如果您的图像格式是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图像用于屏幕输出。