【问题标题】:Resize image while preserving mimetype using .Net使用 .Net 在保留 mimetype 的同时调整图像大小
【发布时间】:2010-08-20 10:11:09
【问题描述】:

我正在从数据库加载图像,并希望根据某些输入动态调整它们的大小。

代码是这样的:

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);
    }

如何以保留编码类型等的方式实现 Resize?我查看了Image resizing efficiency in C# and .NET 3.5,但看不到它会如何保留编码 - 因为创建新的位图肯定不会被编码?

【问题讨论】:

  • 标题建议您要保留 mimetype,但问题本身涉及编码类型(我假设是文件格式)。你想保留什么?
  • 在下面查看我的答案。编码是指编解码器格式。

标签: c# asp.net-mvc-2 image-processing resize


【解决方案1】:

事实是,我最终在谷歌的帮助下设法解决了这个问题。猜猜我对这个问题有点太高兴了。无论如何,基本位是我使用 ImageCodecInfo.GetImageEncoders() 从 mimetype 中查找正确的 ImageFormat,然后使用正确的编码保存,如下所示:

    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;
    }

这是我在http://www.switchonthecode.com/tutorials/csharp-tutorial-image-editing-saving-cropping-and-resizing 上制作的代码版本略有不同

使用 ImageFormat 我可以轻松做到

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

【讨论】:

    【解决方案2】:

    要保留文件类型,您必须查看原始文件的文件类型,并在保存文件时指定文件格式。

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

    在您的情况下,您可能会保存到稍后转换为字节数组的 MemoryStream(猜测您的 info.Databyte[] 类型)。

    【讨论】:

      猜你喜欢
      • 2011-04-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-20
      • 1970-01-01
      • 1970-01-01
      • 2016-06-22
      • 1970-01-01
      • 2021-06-12
      相关资源
      最近更新 更多