Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine file type from ImageFormat.MemoryBMP

Tags:

c#

asp.net

image

After resizing an image, my resize function returns a newly drawn Image. I'm running into an issue where I need to determine what the file extension of the returned Image should be. I was using the Image.RawFormat property previously but everytime an Image is returned from this function it has ImageFormat.MemoryBMP, rather than ImageFormat.Jpeg or ImageFormat.Gif for example.

So basically my question is, how can I determine what file type the newly resized Image should be?

public static Image ResizeImage(Image imageToResize, int width, int height)
        {
            // Create a new empty image
            Image resizedImage = new Bitmap(width, height);

            // Create a new graphic from image
            Graphics graphic = Graphics.FromImage(resizedImage);

            // Set graphics modes
            graphic.SmoothingMode = SmoothingMode.HighQuality;
            graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;

            // Copy each property from old iamge to new image
            foreach (var prop in imageToResize.PropertyItems)
            {
                resizedImage.SetPropertyItem(prop);
            }

            // Draw the new Image at the resized size
            graphic.DrawImage(imageToResize, new Rectangle(0, 0, width, height));

            // Return the new image
            return resizedImage;
        }
like image 611
Chris Avatar asked Sep 26 '11 00:09

Chris


1 Answers

The resized image is not in any file based format, it is an uncompressed memory representation of the pixels in the image.

To save this image back to disk the data needs to be encoded in the selected format, which you have to specify. Look at the Save method, it takes an ImageFormat as a second argument, make that Jpeg or whatever format best fits your application.

like image 79
Miguel Avatar answered Oct 14 '22 07:10

Miguel