Search code examples
c#imagebitmapimage-resizingsystem.drawing

Resizing and Watermark Image in C#


i want to watermark pictures with different sizes in one folder. the watermark has 3891 x 4118 pixels. the pictures i want to watermark have nearly the same size or way lower.

however, the watermark image should always have the same size on the images. therefore i take the width of image i want to watermark, multiple it by 0.2 (20%) and the height of the watermark image gets calculated by the ratio. (see code below).

after that, i resize the watermark image and put it on on the image i want to watermark. so far so good, but the problem is, that the image is way smaller than it should be. the calculation works fine, even if i say, put the image as is (3891 x 4118 pixel), it calculates it correctly, but the watermark doesn't get bigger. it stays on a size i didn't calulcate.

that's the button to load the folder.

 private void DateiLaden_Click(object sender, RoutedEventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            DialogResult result = fbd.ShowDialog();


            try
            {
                string[] files = GetFiles(fbd.SelectedPath.ToString(), "*.jpg|*.jpeg"); //Only select JPG pictures, method below

                int anzahlBilder = files.Length;
                if (anzahlBilder <= 0)
                {
                    System.Windows.Forms.MessageBox.Show("No images!");
                } // if there are no images, stop processing...
                else
                {
                    var res = checkImageSize(files); //check if they have a minmal size, method below
                    if (res == "") //if everythings fine, continue
                    {
                        Directory.CreateDirectory(fbd.SelectedPath.ToString() + "\\watermarked"); //create new directory of the selected folder, folder so save the watermarked images


                        System.Drawing.Image brand = System.Drawing.Image.FromFile("../../watermark.png"); //load watermark
                        double imageHeightBrand = Convert.ToDouble(brand.Height); //get height (4118px)
                        double imageWidthBrand = Convert.ToDouble(brand.Width); //get width (3891px)
                        double ratioBrand = imageWidthBrand / imageHeightBrand; //get ratio (0.94487615347)

                        foreach (var file in files)
                        {
                            System.Drawing.Image img = System.Drawing.Image.FromFile(file); //load image to watermerk to get width and height

                            double imageHeightBild = Convert.ToDouble(img.Height); //height of the image to watermark
                            double imageWidthBild = Convert.ToDouble(img.Width);  //width of the image to watermark                 

                             //Landscape
                             if (imageWidthBild > 640.0 && imageHeightBild > 425.0)
                             {
                                 var imageWidthTmpBranding = imageWidthBild * 0.2; //the watermark width, but only 20% size of the image to watermark
                                 var imageHeightTmpBranding = imageWidthTmpBranding / ratioBrand; //height of watermark, preserve aspect ratio

                                 int imageWidthBranding = Convert.ToInt32(imageWidthTmpBranding); //convert in into int32 (see method below)
                                 int imageHeightBranding = Convert.ToInt32(imageHeightTmpBranding); //convert in into int32 (see method below)


                                 var watermark = ResizeImage(brand, imageWidthBranding, imageHeightBranding); //resize temporally the watermark image, method below

                                 System.Drawing.Image image = System.Drawing.Image.FromFile(file); //get image to watermark
                                 Graphics g = Graphics.FromImage(image); //load is as graphic
                                 g.DrawImage(watermark, new System.Drawing.Point(50, 50)); //draw the watermark on it
                                 image.Save(fbd.SelectedPath.ToString() + "\\watermarked\\" + returnOnlyImageName(file)); //save it in the folder with the same file name, see method below.
                             }

                            //Portrait
                           /* if(imageWidthBild > 350 && imageHeightBild > 520) {

                            }*/

                        }
                    }
                    else
                    {
                        System.Windows.Forms.MessageBox.Show(res);
                    }

                }

            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }


        }

"methods below"

 private static string[] GetFiles(string sourceFolder, string filters)
        {
            return filters.Split('|').SelectMany(filter => System.IO.Directory.GetFiles(sourceFolder, filter)).ToArray();
        }

        private static string checkImageSize(string[] files)
        {

            string message = "The following pictures are too small:\n";


            foreach (var file in files)
            {
                Bitmap img = new Bitmap(file);

                var imageHeight = img.Height;
                var imageWidth = img.Width;

                if ((imageWidth < 640 && imageHeight < 425) || (imageWidth < 350 && imageHeight < 520))
                {
                    message += returnOnlyImageName(file) + "\n";
                }
            }

            if (message == "The following pictures are too small:\n")
            {
                return "";
            }
            else
            {
                message += "\nPlease change those pictures!";
                return message;
            }

        }

        private static string returnOnlyImageName(string file)
        {
            return file.Substring(file.LastIndexOf("\\")+1);
        }

        public static Bitmap ResizeImage(System.Drawing.Image image, int width, int height)
        {
            var destRect = new System.Drawing.Rectangle(0, 0, width, height);
            var destImage = new Bitmap(width, height);

            destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

            using (var graphics = Graphics.FromImage(destImage))
            {
                graphics.CompositingMode = CompositingMode.SourceCopy;
                graphics.CompositingQuality = CompositingQuality.HighQuality;
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode = SmoothingMode.HighQuality;
                graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

                using (var wrapMode = new ImageAttributes())
                {
                    wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                    graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
                }
            }

            return destImage;
        }

and is it also anyhow possible to save all the watermarks in the bottom right corner?

thanks in regards


Solution

  • Here you go...

    void waterMarkOnBottomRight(Image img, Image watermarkImage, string saveFileName)
        {
            double imageHeightBrand = Convert.ToDouble(watermarkImage.Height);
            double imageWidthBrand = Convert.ToDouble(watermarkImage.Width);
            double ratioBrand = imageWidthBrand / imageHeightBrand;
    
            double imageHeightBild = Convert.ToDouble(img.Height); //height of the image to watermark
            double imageWidthBild = Convert.ToDouble(img.Width);
            var imageWidthTmpBranding = imageWidthBild * 0.2; //the watermark width, but only 20% size of the image to watermark
            var imageHeightTmpBranding = imageWidthTmpBranding / ratioBrand; //height of watermark, preserve aspect ratio
            int imageWidthBranding = Convert.ToInt32(imageWidthTmpBranding); //convert in into int32 (see method below)
            int imageHeightBranding = Convert.ToInt32(imageHeightTmpBranding);
    
            int watermarkX = (int)(imageWidthBild - imageWidthBranding); // Bottom Right
            int watermarkY = (int)(imageHeightBild - imageHeightBranding);
    
            using (Graphics g = Graphics.FromImage(img)) 
                g.DrawImage(watermarkImage,
                    new Rectangle(watermarkX, watermarkY, imageWidthBranding, imageHeightBranding),
                    new Rectangle(0, 0, (int)imageWidthBrand, (int)imageHeightBrand),
                    GraphicsUnit.Pixel);
            img.Save(saveFileName);
        }
    

    This one's working for landscape (width > height).

    Well.. in your code, you don't have to create separate instances for images for calculating, for creating graphics, add a new bitmap and paint using graphics and all. You do anything with the image, its in the memory. And its not going to affect the watermark image on your disk.