使用ImageResizer.net确定图像的当前大小。

5
我们最近开始在ASP.NET MVC 4应用程序中使用ImageResizer.Net来动态调整图像大小,而不是使用GDI+。
只使用ImageResizer,有没有一种方法可以确定图像的实际分辨率(DPI、PPI或其他任何你想称呼它的方式)(读取为字节数组的图像)? 当需要时,我们当前有这样的工作流程,将图像调整为指定的较低分辨率:
//pseudo-code
var image = (Bitmap)Bitmap.FromStream(contentStream)
var resX = image.HorizontalResolution;
var resY = image.VerticalResolution;
//calculate scale factor
//determine newHeight and newWidth from scale
var settings = new ResizeSettings("width={newWidth}&height={newHeight}")
var newImage = ImageBuilder.Current.Build(image, someNewImage, settings);

这个可以正常工作,但它混合了GDI+和ImageResizer,并且对相同数据进行了许多流的打开和关闭(实际代码有点冗长,有许多using语句)。
有没有办法只使用ImageResizer来确定水平和垂直分辨率?我在文档中没有立即找到任何内容。
目前,我们已经使用了托管API,但最终将使用MVC路由。

通常,嵌入式DPI值是不正确或无用的。除非您仅使用某些图像格式并且已经完全控制了它们的编码方式,否则我不认为您可以在计算中依赖它们。您能否更详细地解释一下您的使用场景? - Lilith River
我们有合同义务,只在通过某种方式访问时提供最大96dpi的图像。我们通过将图像缩小到该dpi下的大小,然后在“Bitmap”类上设置分辨率来实现这一点。这似乎适用于PNG和JPG图像,并且需要缩放的图像的来源已知(即:不是用户上传的)。 - Thomas Jones
2个回答

3
这是一个相当不典型的情况 - 通常来说,传入的DPI值是没有意义的。
然而,由于似乎您可以控制这些值,并且需要它们来执行大小计算,我建议使用插件。它们很容易使用,并且提供了理想的性能,因为您不会重复努力。
public class CustomSizing:BuilderExtension, IPlugin {

    public CustomSizing() { }

    public IPlugin Install(Configuration.Config c) {
        c.Plugins.add_plugin(this);
        return this;
    }

    public bool Uninstall(Configuration.Config c) {
        c.Plugins.remove_plugin(this);
        return true;
    }
    //Executes right after the bitmap has been loaded and rotated/paged
    protected override RequestedAction PostPrepareSourceBitmap(ImageState s) {
        //I suggest only activating this logic if you get a particular querystring command.
        if (!"true".Equals(s.settings["customsizing"], 
            StringComparison.OrdinalIgnoreCase)) return RequestedAction.None;

        //s.sourceBitmap.HorizontalResolution
        //s.sourceBitmap.VerticalResolution

        //Set output pixel dimensions and fit mode
        //s.settings.Width = X;
        //s.settings.Height = Y;
        //s.settings.Mode = FitMode.Max;

        //Set output res.
        //s.settings["dpi"] = "96";
        return RequestedAction.None;
    }
 }

安装可以通过代码或Web.Config进行。

new CustomSizing().Install(Config.Current);

或者在Resizer的配置部分中:

   <plugins>
     <add name="MyNamespace.CustomSizing" />
   </plugins>

虽然我们还没有实现这个功能,但我认为这是最简单/最可靠的方法。答案似乎提供了所有必要的信息。谢谢。 - Thomas Jones

1

它如何给出原始大小?看起来它希望你将其提供给函数。 - Dani

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接