Q:

set watermark on an image with high quality

I have a handler wich set watermark on images. The problem is the quality is not so good.
Here is the code:
    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();
    }

How can I set the quality for the result?
Thank you,
Alina

A:

If your image format is a Jpeg, then you can set the output quality manually by using this sample method to save to disk:
    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);
    }

Or, in your case, use the following piece of code:
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();
    }

In general, a quality of 60 to 100 should produce good enough Jpeg images for screen output.

