Thomas Jones
Thomas Jones

Reputation: 4962

Determine current size of image using ImageResizer.net

We have recently started using ImageResizer.Net over GDI+ for dynamically resizing images on our ASP.NET MVC 4 application.

Is there a way, using only ImageResizer, to determine the actual resolution(DPI,PPI, whatever you want to call it), of the image (which is read in as a byte array). We currently have a workflow like this, to resize the image to a specified lower resolution when needed:

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

This works fine, but its mixing GDI+ and ImageResizer, and has alot of stream opening and closing of the same data (the actual code is a bit more verbose, with many using statements).

Is there a way to determine the Horizontal and Vertical Resolution using just ImageResizer? I couldn't immediately find anything in the documentation.

For the moment, we have used the managed api, but will eventually use the MVC routing.

Upvotes: 5

Views: 2515

Answers (2)

Lilith River
Lilith River

Reputation: 16468

This is a rather atypical scenario - normally incoming DPI values are worthless.

However, since it appears you control those values, and need them to perform sizing calculations, I suggest a plugin. They're easy, and offer ideal performance since you're not duplicating effort.

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

Installation can be done through code or via Web.Config.

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

or in the resizer's configuration section:

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

Upvotes: 3

Related Questions