locked
Saving any picture format to a specific format RRS feed

  • Question

  • User-1397778012 posted

    Hi there,

    I am using GD+ to resize images that can be uploaded as any image format. I want to save them all as JPG images. Is that not possible using something like this? I keep getting an argument exception when I try to save the images.

    Bitmap tempThumbBitmap = (Bitmap)this.originalImage;
    tempThumbBitmap.Save("myImage.JPG", ImageFormat.Jpeg);

     

    Thursday, July 8, 2010 10:56 AM

Answers

  • User1211441112 posted

    using System.Drawing;
    using System.Drawing.Drawing2D;

            public void ResizeStream(int imageSize, Stream filePath, string outputPath)
            {
                var image = Image.FromStream(filePath);

                int thumbnailSize = imageSize;
                int newWidth, newHeight;

                if (image.Width > image.Height)
                {
                    newWidth = thumbnailSize;
                    newHeight = image.Height * thumbnailSize / image.Width;
                }
                else
                {
                    newWidth = image.Width * thumbnailSize / image.Height;
                    newHeight = thumbnailSize;
                }

                var thumbnailBitmap = new Bitmap(newWidth, newHeight);

                var thumbnailGraph = Graphics.FromImage(thumbnailBitmap);
                thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
                thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;
                thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;

                var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
                thumbnailGraph.DrawImage(image, imageRectangle);

                thumbnailBitmap.Save(outputPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                thumbnailGraph.Dispose();
                thumbnailBitmap.Dispose();
                image.Dispose();
            }

    then call resize image function as

    ResizeImage(400, File1.FileContent, path);

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, July 16, 2010 1:46 AM