views:

20

answers:

2

Hi. I am loading images from a database and want to dynamically resize them according to some input.

Code is something like this:

public ActionResult GetImage(string imageID, int? width, int? height, bool constrain)
    {
        ValidateImageInput(width, height, constrain);
        ImageWithMimeType info = LoadFromDatabase(imageID);

        if(info == null)
            throw new HttpException(404, "Image with that name or id was not found.");

        Resize(info.Bytedata, width, height, constrain, info.MimeType);

        return File(info.Data, info.MimeType);
    }

How would I implement Resize in a way that preserves encoding type etc? I've looked at http://stackoverflow.com/questions/1357257/image-resizing-efficiency-in-c-and-net-3-5 but don't see how it would preserve encoding - since creating a new Bitmap surely isn't encoded?

A: 

To preserve the filetype you have to look at that filetype the original file has and when saving the file you specify the file format.

Bitmap b = new Bitmap("foo.jpg");
b.Save("bar.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

In your case you would probably save to an MemoryStream that you later convert to the byte array (guessing that your info.Data is of type byte[]).

Albin Sunnanbo
A: 

Fact is, I managed to solve it with some help of google eventually. Guess I was a bit too trigger happy with the question. Anyway, the basic bits is that I look up the proper ImageFormat from the mimetype using ImageCodecInfo.GetImageEncoders(), then save using the correct encoding, as following:

    private ImageFormat GetEncoderInfo(string mimeType)
    {
        // Get image codecs for all image formats
        ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

        // Find the correct image codec
        for (int i = 0; i < codecs.Length; i++)
            if (codecs[i].MimeType == mimeType)
                return new ImageFormat(codecs[i].FormatID);
        return null;
    }

This is a slightly different version I made of the code on http://www.switchonthecode.com/tutorials/csharp-tutorial-image-editing-saving-cropping-and-resizing

Using the ImageFormat I can simply do

image.Save(dest, GetEncoderInfo(mimetype));
Max Malmgren