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)
{
ValidateImageIn开发者_高级运维put(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 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?
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));
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[]
).
精彩评论