locked
Altering an images size... RRS feed

  • Question

  • User2137615476 posted

    I wnat to save an image and an image half it's size to a database. I already have the original image being saved to the database by generating a byte[] and saving the stream that way and saving the content type, but I want to create a smaller version of the image (50%) and a thumbnail (thus, there will be 3 versions). I am not familiar with the System.Drawing class or any of the methods associated with it. If someone can provide me with a good resource or any insight into how I would go about doing this, I would appreciate the help very much.

    Thanks in advance.

    Friday, July 7, 2006 12:20 PM

All replies

  • User-437536345 posted

    Try to use this sample code, you can use the same method to get smaller version of the image and the thumbnail

    private bool DummyCallBack ( )

    {

    return false ;

    }

    private void Form1_Load(object sender, EventArgs e)

    {

    Image img = Image.FromFile ( "original.jpg" ) ;

    Image thumbnail = img.GetThumbnailImage ( img.Width / 2, img.Height / 2, new Image.GetThumbnailImageAbort(DummyCallBack), IntPtr.Zero );

    thumbnail.Save ( "thumbs.jpg" ) ;

    }

     

    hope it helps

    Friday, July 7, 2006 2:32 PM
  • User2137615476 posted
    Thanks. I don't really have any problem with the thumbs. I want to grab a jpg or gif image and make an image from it half it's size upon submission to the gallery.
    Friday, July 7, 2006 9:14 PM
  • User-1363174918 posted

    I don't have code snippet handy, but the idea is

    1. Create smaller Image object

    2. Create Graphics object from this image, see Graphics.FromImage

    3. Draw original image on this graphics object, see Graphics.DrawImage

    4. Save new small image via Image.Save. 

    Saturday, July 8, 2006 6:52 PM
  • User1900948409 posted
    GetThumbnail sucks. if it's a photo with a thumbnail already stored in a stream in the file, it'll grab that.

    try this:

                        //---- declare vars
                        System.Drawing.Image objThumbnail = new Bitmap(width, height, PixelFormat.Format24bppRgb);
                        using (Graphics objGraphic = Graphics.FromImage(objThumbnail)) // drawing surface of the same format as our image
                        {
                            Rectangle objRectangle = new Rectangle(0, 0, width, height);

                            //---- set our options for the drawing surface
                            objGraphic.CompositingQuality = CompositingQuality.HighQuality;
                            objGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;

                            //---- draw the thumbnail onto the graphics surface at our new size.
                            objGraphic.DrawImage(image, objRectangle);

                            return objThumbnail;
                        }

    Saturday, July 15, 2006 7:12 PM
  • User2026432229 posted
    Hi Bryan, I found a script that converts a regular size image to a thumbnail. It's a wonderful script, except the thumbnail quality is a bit low. I'd like to add the following code to improve the output quality of the thumbnail. Can someone direct me where to incorporate this code? Code to insert: graphic.InterpolationMode = InterpolationMode.HighQualityBicubic; graphic.SmoothingMode = SmoothingMode.HighQuality; graphic.PixelOffsetMode = PixelOffsetMode.HighQuality; graphic.CompositingQuality = CompositingQuality.HighQuality; Thanks. Original script: < % @ Page Language="C#" ContentType="text/html" ResponseEncoding="iso-8859-1" %> void Page_Load(Object sender, EventArgs e) { try{ Response.Cache.VaryByParams["Image;Width;Height;ForceAspect"] = true; Response.ContentType = "image/jpeg"; System.Collections.Hashtable imageOutputFormatsTable = new System.Collections.Hashtable(); imageOutputFormatsTable.Add(System.Drawing.Imaging.ImageFormat.Gif.Guid, System.Drawing.Imaging.ImageFormat.Gif); imageOutputFormatsTable.Add(System.Drawing.Imaging.ImageFormat.Jpeg.Guid, System.Drawing.Imaging.ImageFormat.Jpeg); imageOutputFormatsTable.Add(System.Drawing.Imaging.ImageFormat.Bmp.Guid, System.Drawing.Imaging.ImageFormat.Gif); imageOutputFormatsTable.Add(System.Drawing.Imaging.ImageFormat.Tiff.Guid, System.Drawing.Imaging.ImageFormat.Jpeg); imageOutputFormatsTable.Add(System.Drawing.Imaging.ImageFormat.Png.Guid, System.Drawing.Imaging.ImageFormat.Jpeg); string imageLocation; bool forceaspect = true; int newHeight; int newWidth; int reqHeight = 100; int reqWidth = 100; int origHeight; int origWidth; imageLocation = Server.MapPath(Request.QueryString["Image"]); if (Request.QueryString["Height"] != null){ reqHeight = Convert.ToInt32(Request.QueryString["Height"]); } if (Request.QueryString["ForceAspect"] != null){ forceaspect = Convert.ToBoolean(Request.QueryString["ForceAspect"]); } if(Request.QueryString["Width"] != null){ reqWidth = Convert.ToInt32(Request.QueryString["Width"]); } if (Request.QueryString["ForceAspect"] == "true"){ forceaspect = true; } System.Drawing.Bitmap origBitmap = new System.Drawing.Bitmap(imageLocation); origHeight = origBitmap.Height; origWidth = origBitmap.Width; if (forceaspect){ //Force Aspect Change newHeight = reqHeight; newWidth = reqWidth; } else if (origBitmap.Height >= origBitmap.Width){ //Portrait newHeight = reqHeight; newWidth = (int)(((double)origBitmap.Width / (double)origBitmap.Height) * reqHeight); } else{ //Landscape newWidth = reqWidth; newHeight = (int)(((double)origBitmap.Height / (double)origBitmap.Width) * reqWidth); } System.Drawing.Bitmap outputImage = new System.Drawing.Bitmap(origBitmap, newWidth, newHeight); outputImage.SetResolution(72, 72); //outputImage.InterpolationMode = InterpolationMode.HighQualityBicubic; // does not work ! System.Drawing.Imaging.ImageFormat outputFormat = (System.Drawing.Imaging.ImageFormat)imageOutputFormatsTable[origBitmap.RawFormat.Guid]; outputImage.Save(Response.OutputStream, outputFormat); outputImage.Dispose(); origBitmap.Dispose(); } catch (Exception ex){ //log error so we may know the problem. you need to have write permits, of course on log path System.IO.StreamWriter sw=null; try{ sw=new System.IO.StreamWriter(Server.MapPath("error.txt"),true); sw.WriteLine("Error : " + ex.Message + " processing " + Request.QueryString["Image"]); } catch{} finally{sw.Close();} //now display the error image Response.Redirect("thumberror.gif"); } } // ----------------------------------------------------------------------- <bryanc> wrote in message news:1342358@forums.asp.net... GetThumbnail sucks. if it's a photo with a thumbnail already stored in a stream in the file, it'll grab that. try this: //---- declare vars System.Drawing.Image objThumbnail = new Bitmap(width, height, PixelFormat.Format24bppRgb); using (Graphics objGraphic = Graphics.FromImage(objThumbnail)) // drawing surface of the same format as our image { Rectangle objRectangle = new Rectangle(0, 0, width, height); //---- set our options for the drawing surface objGraphic.CompositingQuality = CompositingQuality.HighQuality; objGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic; //---- draw the thumbnail onto the graphics surface at our new size. objGraphic.DrawImage(image, objRectangle); return objThumbnail; } http://forums.asp.net/1335992/ShowThread.aspx#1342358
    Friday, September 29, 2006 1:04 PM
  • User1900948409 posted

    you probably want to modify this bit of code:

    System.Drawing.Bitmap outputImage = new System.Drawing.Bitmap(origBitmap,
    newWidth, newHeight);
    outputImage.SetResolution(72, 72);

    and do something more like the example i had up above.

                        //---- declare vars
                        System.Drawing.Image objThumbnail = new Bitmap(width, height, PixelFormat.Format24bppRgb);
                        using (Graphics objGraphic = Graphics.FromImage(objThumbnail)) // drawing surface of the same format as our image
                        {
                            Rectangle objRectangle = new Rectangle(0, 0, width, height);

                            //---- set our options for the drawing surface
                            objGraphic.CompositingQuality = CompositingQuality.HighQuality;
                            objGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;

                            //---- draw the thumbnail onto the graphics surface at our new size.
                            objGraphic.DrawImage(image, objRectangle);

                            return objThumbnail;
                        }

     

     Incidentally, here is the code from my imagemanager class which does exactly what you're looking for (resizing images with height/width constraints):

     

        /// <summary>
        /// Summary description for ImageManager.
        /// </summary>
        public class ImageManager
        {
            //=========================================================================
            #region -= constructors =-
            //=========================================================================
            protected ImageManager() { }
            //=========================================================================

            //=========================================================================
            static ImageManager() { }
            //=========================================================================
            #endregion
            //=========================================================================

            //=========================================================================
            #region -= methods =-

            //=========================================================================
            public static System.Drawing.Image GetThumbnail(int maxSize, string imagePath)
            {
                using (Image img = Image.FromFile(imagePath))
                {
                    return GetThumbnail(maxSize, img);
                }           
            }
            //=========================================================================

            //=========================================================================
            public static System.Drawing.Image GetThumbnail(Constraint constraint, int maxSize, string imagePath)
            {
                using (Image img = Image.FromFile(imagePath))
                {
                    return GetThumbnail(constraint, maxSize, img);
                }
            }
            //=========================================================================

            //=========================================================================
            public static System.Drawing.Image GetThumbnail(int maxSize, System.Drawing.Image image)
            {
                return GetThumbnail(maxSize, image, false);
            }
            //=========================================================================

            //=========================================================================
            public static System.Drawing.Image GetThumbnail(int maxSize, System.Drawing.Image image, bool forceJpegOutput)
            {
                if (image.Width > image.Height)
                    return GetThumbnail(Constraint.Width, maxSize, image);
                else
                    return GetThumbnail(Constraint.Height, maxSize, image);
            }
            //=========================================================================

            //=========================================================================
            /// <summary>
            /// </summary>
            /// <param name="constraint">The constraint, whether width or height, that you want to enforce.</param>
            /// <param name="maxSize"></param>
            /// <param name="image"></param>
            /// <returns></returns>
            public static System.Drawing.Image GetThumbnail(Constraint constraint, int maxSize, System.Drawing.Image image)
            {
                return GetThumbnail(constraint, maxSize, image, false);
            }
            //=========================================================================

            //=========================================================================
            public static System.Drawing.Image GetThumbnail(Constraint constraint, int maxSize, System.Drawing.Image image, bool forceJpegOutput)
            {
                //----
                if (constraint == Constraint.Height)
                {
                    int width = (int)(maxSize * GetImageRatio(image.Width, image.Height));
                    return GetThumbnail(width, maxSize, image, forceJpegOutput);
                }
                else
                {
                    int height = (int)(maxSize / GetImageRatio(image.Width, image.Height));
                    return GetThumbnail(maxSize, height, image, forceJpegOutput);
                }
            }
            //=========================================================================
           
            //=========================================================================
            /// <summary>
            /// This method is a backup for getting a thumbnail of an image. The other one will produce higher
            /// quality images, but will not work with certain formats, such as indexed formats (gif). so we try the other
            /// one and if it fails, we try this one.
            /// </summary>
            /// <param name="width"></param>
            /// <param name="height"></param>
            /// <param name="image"></param>
            /// <returns></returns>
            private static System.Drawing.Image GetThumbnail2(int width, int height, System.Drawing.Image image)
            {
                //---- declare vars
                System.Drawing.Image objThumbnail;
                //---- get the thumbnail
                objThumbnail = image.GetThumbnailImage(width, height, null, IntPtr.Zero);
                //---- return the thumbnail
                return objThumbnail;
            }
            //=========================================================================

            //=========================================================================
            /// <summary>
            ///
            /// </summary>
            /// <param name="width"></param>
            /// <param name="height"></param>
            /// <param name="image"></param>
            /// <returns></returns>
            public static System.Drawing.Image GetThumbnail(int width, int height, System.Drawing.Image image)
            {
                try
                {
                    //---- declare vars
                    System.Drawing.Image objThumbnail = new Bitmap(width, height, image.PixelFormat);

                    using (Graphics objGraphic = Graphics.FromImage(objThumbnail)) // drawing surface of the same format as our image
                    {
                        Rectangle objRectangle = new Rectangle(0, 0, width, height);

                        //---- set our options for the drawing surface
                        objGraphic.CompositingQuality = CompositingQuality.HighQuality;
                        objGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;

                        //---- draw the thumbnail onto the graphics surface at our new size.
                        objGraphic.DrawImage(image, objRectangle);

                        return objThumbnail;
                    }

                }
                catch
                {
                    return GetThumbnail2(width, height, image);
                }

            }
            //=========================================================================

            //=========================================================================
            /// <summary>
            /// Same as other GetThumbnail, but gives the option to output a jpg file instead of preserving the format
            /// that came in.
            /// </summary>
            /// <param name="width"></param>
            /// <param name="height"></param>
            /// <param name="image"></param>
            /// <param name="forceJpegOutput">true if you want a JPEG out.</param>
            /// <returns></returns>
            public static System.Drawing.Image GetThumbnail(int width, int height, System.Drawing.Image image, bool forceJpegOutput)
            {
                if (!forceJpegOutput)
                    return GetThumbnail(width, height, image);
                else
                {

                    try
                    {
                        //---- declare vars
                        System.Drawing.Image objThumbnail = new Bitmap(width, height, PixelFormat.Format24bppRgb);
                        using (Graphics objGraphic = Graphics.FromImage(objThumbnail)) // drawing surface of the same format as our image
                        {
                            Rectangle objRectangle = new Rectangle(0, 0, width, height);

                            //---- set our options for the drawing surface
                            objGraphic.CompositingQuality = CompositingQuality.HighQuality;
                            objGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;

                            //---- draw the thumbnail onto the graphics surface at our new size.
                            objGraphic.DrawImage(image, objRectangle);

                            return objThumbnail;
                        }
                    }
                    catch
                    {
                        return GetThumbnail2(width, height, image);
                    }
                }
            }
            //=========================================================================

            //=========================================================================
            public static string GetImageFileExtension(System.Drawing.Image objImage)
            {
                //This function gets the file extension by reading the image format of the image object
                string strFileExt = ".bmp";
                if (objImage.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Bmp))
                { strFileExt = ".bmp"; }
                else if (objImage.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Gif))
                { strFileExt = ".gif"; }
                else if (objImage.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Emf))
                { strFileExt = ".emf"; }
                else if (objImage.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Exif))
                { strFileExt = ".exif"; }
                else if (objImage.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Icon))
                { strFileExt = ".ico"; }
                else if (objImage.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg))
                { strFileExt = ".jpg"; }
                else if (objImage.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Png))
                { strFileExt = ".png"; }
                else if (objImage.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Tiff))
                { strFileExt = ".tiff"; }
                else if (objImage.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Wmf))
                { strFileExt = ".wmf"; }

                return strFileExt;
            }
            //=========================================================================

            //=========================================================================
            static private double GetImageRatio(int width, int height)
            {
                double ratio = ((double)width / (double)height);
                return ratio;
            }
            //=========================================================================

            #endregion
            //=========================================================================

            //=========================================================================
            #region -= enums =-
            public enum Constraint
            {
                Width,
                Height
            }
            #endregion
            //=========================================================================

        }

     

     

    Friday, September 29, 2006 2:19 PM
  • User2026432229 posted
    Thanks for your quick reply, Brian. If possible, could you update the original code that I posted by incorporating the calls that you suggested? I basically want to improve the thumbnail quality by setting the CompositingQuality.HighQuality and InterpolationMode.HighQualityBicubic. That would be very very helpful. Thanks again! <bryanc> wrote in message news:1414357@forums.asp.net... you probably want to modify this bit of code: System.Drawing.Bitmap outputImage = new System.Drawing.Bitmap(origBitmap, newWidth, newHeight); outputImage.SetResolution(72, 72); and do something more like the example i had up above. //---- declare vars System.Drawing.Image objThumbnail = new Bitmap(width, height, PixelFormat.Format24bppRgb); using (Graphics objGraphic = Graphics.FromImage(objThumbnail)) // drawing surface of the same format as our image { Rectangle objRectangle = new Rectangle(0, 0, width, height); //---- set our options for the drawing surface objGraphic.CompositingQuality = CompositingQuality.HighQuality; objGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic; //---- draw the thumbnail onto the graphics surface at our new size. objGraphic.DrawImage(image, objRectangle); return objThumbnail; } Incidentally, here is the code from my imagemanager class which does exactly what you're looking for (resizing images with height/width constraints): /// <summary> /// Summary description for ImageManager. /// </summary> public class ImageManager { //========================================================================= #region -= constructors =- //========================================================================= protected ImageManager() { } //========================================================================= //========================================================================= static ImageManager() { } //========================================================================= #endregion //========================================================================= //========================================================================= #region -= methods =- //========================================================================= public static System.Drawing.Image GetThumbnail(int maxSize, string imagePath) { using (Image img = Image.FromFile(imagePath)) { return GetThumbnail(maxSize, img); } } //========================================================================= //========================================================================= public static System.Drawing.Image GetThumbnail(Constraint constraint, int maxSize, string imagePath) { using (Image img = Image.FromFile(imagePath)) { return GetThumbnail(constraint, maxSize, img); } } //========================================================================= //========================================================================= public static System.Drawing.Image GetThumbnail(int maxSize, System.Drawing.Image image) { return GetThumbnail(maxSize, image, false); } //========================================================================= //========================================================================= public static System.Drawing.Image GetThumbnail(int maxSize, System.Drawing.Image image, bool forceJpegOutput) { if (image.Width > image.Height) return GetThumbnail(Constraint.Width, maxSize, image); else return GetThumbnail(Constraint.Height, maxSize, image); } //========================================================================= //========================================================================= /// <summary> /// </summary> /// <param name="constraint">The constraint, whether width or height, that you want to enforce.</param> /// <param name="maxSize"></param> /// <param name="image"></param> /// <returns></returns> public static System.Drawing.Image GetThumbnail(Constraint constraint, int maxSize, System.Drawing.Image image) { return GetThumbnail(constraint, maxSize, image, false); } //========================================================================= //========================================================================= public static System.Drawing.Image GetThumbnail(Constraint constraint, int maxSize, System.Drawing.Image image, bool forceJpegOutput) { //---- if (constraint == Constraint.Height) { int width = (int)(maxSize * GetImageRatio(image.Width, image.Height)); return GetThumbnail(width, maxSize, image, forceJpegOutput); } else { int height = (int)(maxSize / GetImageRatio(image.Width, image.Height)); return GetThumbnail(maxSize, height, image, forceJpegOutput); } } //========================================================================= //========================================================================= /// <summary> /// This method is a backup for getting a thumbnail of an image. The other one will produce higher /// quality images, but will not work with certain formats, such as indexed formats (gif). so we try the other /// one and if it fails, we try this one. /// </summary> /// <param name="width"></param> /// <param name="height"></param> /// <param name="image"></param> /// <returns></returns> private static System.Drawing.Image GetThumbnail2(int width, int height, System.Drawing.Image image) { //---- declare vars System.Drawing.Image objThumbnail; //---- get the thumbnail objThumbnail = image.GetThumbnailImage(width, height, null, IntPtr.Zero); //---- return the thumbnail return objThumbnail; } //========================================================================= //========================================================================= /// <summary> /// /// </summary> /// <param name="width"></param> /// <param name="height"></param> /// <param name="image"></param> /// <returns></returns> public static System.Drawing.Image GetThumbnail(int width, int height, System.Drawing.Image image) { try { //---- declare vars System.Drawing.Image objThumbnail = new Bitmap(width, height, image.PixelFormat); using (Graphics objGraphic = Graphics.FromImage(objThumbnail)) // drawing surface of the same format as our image { Rectangle objRectangle = new Rectangle(0, 0, width, height); //---- set our options for the drawing surface objGraphic.CompositingQuality = CompositingQuality.HighQuality; objGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic; //---- draw the thumbnail onto the graphics surface at our new size. objGraphic.DrawImage(image, objRectangle); return objThumbnail; } } catch { return GetThumbnail2(width, height, image); } } //========================================================================= //========================================================================= /// <summary> /// Same as other GetThumbnail, but gives the option to output a jpg file instead of preserving the format /// that came in. /// </summary> /// <param name="width"></param> /// <param name="height"></param> /// <param name="image"></param> /// <param name="forceJpegOutput">true if you want a JPEG out.</param> /// <returns></returns> public static System.Drawing.Image GetThumbnail(int width, int height, System.Drawing.Image image, bool forceJpegOutput) { if (!forceJpegOutput) return GetThumbnail(width, height, image); else { try { //---- declare vars System.Drawing.Image objThumbnail = new Bitmap(width, height, PixelFormat.Format24bppRgb); using (Graphics objGraphic = Graphics.FromImage(objThumbnail)) // drawing surface of the same format as our image { Rectangle objRectangle = new Rectangle(0, 0, width, height); //---- set our options for the drawing surface objGraphic.CompositingQuality = CompositingQuality.HighQuality; objGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic; //---- draw the thumbnail onto the graphics surface at our new size. objGraphic.DrawImage(image, objRectangle); return objThumbnail; } } catch { return GetThumbnail2(width, height, image); } } } //========================================================================= //========================================================================= public static string GetImageFileExtension(System.Drawing.Image objImage) { //This function gets the file extension by reading the image format of the image object string strFileExt = ".bmp"; if (objImage.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Bmp)) { strFileExt = ".bmp"; } else if (objImage.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Gif)) { strFileExt = ".gif"; } else if (objImage.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Emf)) { strFileExt = ".emf"; } else if (objImage.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Exif)) { strFileExt = ".exif"; } else if (objImage.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Icon)) { strFileExt = ".ico"; } else if (objImage.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg)) { strFileExt = ".jpg"; } else if (objImage.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Png)) { strFileExt = ".png"; } else if (objImage.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Tiff)) { strFileExt = ".tiff"; } else if (objImage.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Wmf)) { strFileExt = ".wmf"; } return strFileExt; } //========================================================================= //========================================================================= static private double GetImageRatio(int width, int height) { double ratio = ((double)width / (double)height); return ratio; } //========================================================================= #endregion //========================================================================= //========================================================================= #region -= enums =- public enum Constraint { Width, Height } #endregion //========================================================================= } http://forums.asp.net/1414278/ShowThread.aspx#1414357
    Friday, September 29, 2006 5:41 PM