Why's the generated watermarked image is much more bigger than the original image?

124 views Asked by At

I am using the code below to generate a watermarked image, The problem is, the genrated file is always more bigger than the original file even if the dimensions of the generated file are smaller, for example:

original.jpg (1920 * 1440) = 1.11 MB

generated.jpg (960 * 720) = 1.77 MB

Am I missing something?

C# :

private void AddWaterMark(string target, string NewName, string newwidth, string newheight)
{
    Image imgToResize = Image.FromFile(Path.Combine(target, NewName));
    Bitmap indexedImage = new Bitmap(imgToResize, newwidth, newheight);
    Graphics g = Graphics.FromImage(indexedImage);
    g.DrawImage(indexedImage, new Rectangle(0, 0, newwidth, newheight), 0, 0, indexedImage.Width, indexedImage.Height, GraphicsUnit.Pixel);

    g.RotateTransform(-35);

    g.DrawString("WWW.example.COM", new Font("Verdana", 24, FontStyle.Bold), new SolidBrush(Color.FromArgb(75, 255, 255, 255)), -100, 350);
    imgToResize.Dispose();
    indexedImage.Save(target + "\\" + NewName);
    indexedImage.Dispose();
    g.Dispose();

}

VB:

Private Sub AddWaterMark(target As String, NewName As String, newwidth As String, newheight As String)

    Dim imgToResize As Image = Image.FromFile(Path.Combine(target, NewName))
    Dim indexedImage As New Bitmap(imgToResize, newwidth, newheight)
    Dim g As Graphics = Graphics.FromImage(indexedImage)
    g.DrawImage(indexedImage, New Rectangle(0, 0, newwidth, newheight), 0, 0, indexedImage.Width, indexedImage.Height, GraphicsUnit.Pixel)

    g.RotateTransform(-35)

    g.DrawString("WWW.example.COM", New Font("Verdana", 24, FontStyle.Bold), New SolidBrush(Color.FromArgb(75, 255, 255, 255)), -100, 350)
    imgToResize.Dispose()
    indexedImage.Save(target + "\" + NewName)
    indexedImage.Dispose()
    g.Dispose()

End Sub
2

There are 2 answers

1
Christoph Fink On BEST ANSWER

You need to specify a quality, e.g.:

var jpgEncoder = GetEncoder(ImageFormat.Jpeg);
var jpgParameters = new EncoderParameters(1);
jpgParameters.Param[0] = new EncoderParameter(Encoder.Quality, 80L);
indexedImage.Save(target + "\\" + NewName, jpgEncoder, jpgParameters);

and using this method:

private ImageCodecInfo GetEncoder(ImageFormat format)
{
    ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();

    foreach (ImageCodecInfo codec in codecs)
    {
        if (codec.FormatID == format.Guid)
            return codec;
    }
    return null;
}
0
fero On

The JPEG format has a quality factor. You can define how much the resulting image will be compressed. The more it is compressed, the more quality you lose. You can set the quality level in the Save method.

Have a look at the example here: http://msdn.microsoft.com/en-us/library/ytz20d80%28v=vs.110%29.aspx

Samples for different quality levels can be found here: http://en.wikipedia.org/wiki/JPEG#Effects_of_JPEG_compression