c# - How do I resize an image and maintain aspect ratio once its been uploaded? -
i have written method uploading image in mvc application , storing in database. works fine i'd resize image should dimensions exceed limit set. example i'd image no bigger 300px in width if user uploads image that's 1000px need code in method resize it.
there lot of articles couldn't figure out how apply logic i'm doing. i've seen whereby use web helpers , nifty image.resize function.
here method creating database entry contain image.
create method
[httppost] [validateantiforgerytoken] public actionresult create(useraccount useraccount, httppostedfilebase upload) { try { if (modelstate.isvalid) { if (upload != null && upload.contentlength > 0) { var photo = new userimage { filename = system.io.path.getfilename(upload.filename), filetype = filetype.vesselimage, contenttype = upload.contenttype }; using (var reader = new system.io.binaryreader(upload.inputstream)) { photo.content = reader.readbytes(upload.contentlength); } useraccount.userimages = new list<userimage> { photo }; } db.useraccounts.add(useraccount); db.savechanges(); return redirecttoaction("index"); }//if }//try catch (retrylimitexceededexception /* dex */) { modelstate.addmodelerror("", "unable save changes. try again, , if problem persists see system administrator."); } return view(useraccount); }
filetype class
{ public enum filetype { vesselimage = 0, photo } }
create view create view straight forward form file upload input.
@using (html.beginform("create", "useraccounts", null, formmethod.post, new { enctype = "multipart/form-data" })) { @html.antiforgerytoken() <div class="form-horizontal"> <h4>user</h4> <hr /> @html.validationsummary(true, "", new { @class = "text-danger" }) <div class="form-group"> @html.labelfor(model => model.username, htmlattributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @html.editorfor(model => model.username, new { htmlattributes = new { @class = "form-control" } }) @html.validationmessagefor(model => model.username, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @html.labelfor(model => model.userlocation, htmlattributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @html.editorfor(model => model.userlocation, new { htmlattributes = new { @class = "form-control" } }) @html.validationmessagefor(model => model.userlocation, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @html.label("image", new { @class = "control-label col-md-2" }) <div class="col-md-10"> <input type="file" id="vesselimage" name="upload" /> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="create" class="btn btn-default" /> </div> </div> </div>
}
additional resize nice maintain aspect ratio don't know if that's possible.
Comments
Post a Comment