Below is my code to upload and image and save it to be later displayed in a GridView,
How can I resize the image to a small one before saving it if it is too large?
if (this.fuUpload.HasFile == true)
{
string path = Server.MapPath(#"~\images");
string filename = this.fuUpload.FileName;
this.fuUpload.SaveAs(path + #"\" + filename);
this.image.ImageUrl = #"\images\" + filename;
}
Take a look at ImageResizer for ASP.NET:
http://imageresizing.net/
You can use WebImage class built in System.Web.Helpers assembly. Take a look at Working with Images in an ASP.NET Web Pages guide.
Related
I'm new to asp.net and I'm making a website with asp.net mvc 4 where user can upload any type of image(png, jpeg, gif) but system will save the image as a png format. I'm using WebImage helper. So far uploading is working fine but whenever system saves the image, filename looks like this, Filename.png.jpeg. Here is my codes from Controller,
if (file != null && file.ContentLength > 0)
{
string picName = "FileName";
WebImage img = new WebImage(file.InputStream);
if (img.Width > 265 || img.Height > 158)
{
img.Resize(265, 158);
}
string picExt = Path.GetExtension(file.FileName);
if (picExt == ".jpg")
{
picExt = ".png";
}
string path = System.IO.Path.Combine(Server.MapPath("~/Images/"), picName + picExt);
img.Save(path);
}
How can I save the image as only png format no matter what user uploads in any format of image? Need this help badly. Tnx.
I had the same problem, and I just told it to ignore correct extension forcing.
The third parameter is bool forceCorrectExtension which is true by default. You don't need the second parameter since you manually set your extension.
img.Save(path, null, false);
Just ran into the same issue. Please see here:
WebImage.Save Method
Cognis is half correct and it will probably work like that. However, the 2nd parameter actually tells it what format to save as:
imageFormat Type: System.String The format to use when the image file
is saved, such as "gif", or "png".
A jpeg doesn't become a png simply because you change the extension. Unless the Save method knows to reformat based on extension (???), I would rather error on the side of caution by doing:
img.Save(path, "png", false);
I am using dynamic ajax file upload control.
AjaxControlToolkit.AsyncFileUpload()
While i am trying to upload file, in page load the
value of Request.ServerVariables["QUERY_STRING"] is, "AsyncFileUploadID=MainContent_flbFileUpload1&rnd=01846502097323537".
Can anyone tell me, why this happens?
In AsyncFileUpload.pre.js file found in ajaxcontroltoolkit.zip and in _onload: function (e) { .... } has below sample lines which create the resulting postback URL as:
mainForm.action = url + 'AsyncFileUploadID=' + this.get_element().id + '&rnd='
+ Math.random().toString().replace(/\./g, "");
mainForm.target = this._iframeName;
Similar to one of my other questions, but I need clarification.
I have a web application where multiple users will be on at the same time. In the app, an image, which is in one of the app folders, will be drawn on like below, saved, and then added to the image control on the page.
Bitmap image = new Bitmap(Server.MapPath("~") + "/Assets/img/timegrid.jpg");
Graphics graphics = Graphics.FromImage(image);
Pen p = new Pen(Color.Blue, 5);
//draw on image
graphics.DrawLine(p, aPoint, bPoint);
//save new image
image.Save(Server.MapPath("~") + "/Assets/img/newtimegrid.jpg");
imgGrid.ImageUrl = "~/Assets/img/newtimegrid.jpg";
Each user's new image will look different. However, I'm worried that User A will see User B's newtimegrid.jpg instead of his own since every user is saving to the same filename. I've heard of using a generic Image Handler and I've read some of the solutions here, but I still don't understand how to use it, or how to call it if I made one, or if this is even a solution to my problem. Any help would be appreciated.
I would suggest you to keep userID in the session and use this id in the path to uniquely identifying the path of image for each user image path.
You can first check if path already exists for user.
string strDirPath = Server.MapPath("~") + "/Assets/img/ + Session["UserID"].ToString();
if(Directory.Exists(strDirPath))
{
Bitmap image = new Bitmap(strDirPath + "\\" + timegrid.jpg");
//your code here
}
else
{
DirectoryInfo CreateDirectory(strDirPath);
Bitmap image = new Bitmap(strDirPath + "\\" + timegrid.jpg");
//your code here
}
What I am talking about is like this website :
http://www.ernesthemingwaycollection.com
It has a static wallpaper and a set of images that change from page to page, I want to implement a similar way of displaying random images from a set of images using ASP.NET.
EDIT : I want the image to stay the same in a session, and change from a session to another.
The site you mentioned is not using a random set of images. They are coded into the html side of the aspx page.
You could place an asp Image control on your page. Then on the page's Page_Load function set the image to a random picture of your set.
protected void Page_Load(object sender, EventArgs e)
{
this.Image1.ImageUrl = "~/images/random3.jpg";
}
You have different options on where to store the image set data. You could use a database and store the urls in a table. This would allow to use the built-in Random function found in SQL. Or you can save a XML file to the server, load that then use the Random .Net class to pick one of your xml nodes.
Personally i would recommend the Database solution.
EDIT: Because the server session is destroyed after 20mins you may want to look at using cookies so you can see the last random image they saw.
If you just want to rotate a set number of images you could use the ASP.NET AdRotator control (at last, a use for it!).
If you want to do something fancier, considering using a jQuery slideshow such jQuery Cycle Plugin. There is also a slideshow control in the AjaxControlToolkit, which is easy to integrate.
string imageDir = "/images/banner/";
public static string chooseImage(string imageDir)
{
string[] dirs = Directory.GetFiles(HttpContext.Current.Server.MapPath("~/images/" + imageDir + "/"), "*.*");
Random RandString = new Random();
string fileFullPath = dirs[RandString.Next(0, dirs.Length)];
// Do not show Thumbs.db ---
string fileName = string.Empty;
do
{
fileName = System.IO.Path.GetFileName(fileFullPath);
} while (fileName.Contains(".db"));
string imgPath = "/images/" + imageDir + "/" + fileName;
return imgPath;
}
private int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
How to add filter to the fileupload control in asp.net? I want a filter for Word Template File (.dot).
You could also do a javascript alternative to filtering it server side (you'd probably want to do that as well) but this saves the client from spending the time waiting on an upload to finish just to find out it was the wrong type.
http://javascript.internet.com/forms/upload-filter.html
So basically you just run a javascript function on submit that parses off the extension of the uploaded file and gives them an alert if its not of the right type.
You could also use document.forms[0].submit(); instead of passing the form reference through (as ASP.NET really only uses a single form (unless your doing something funky))
string fileName = fuFiles.FileName;
if(fileName.Contains(".dot"))
{
fuFiles.SaveAs(Server.MapPath("~/Files/" + fileName));
}
If you mean to filter the file extensions client/side, with the standard browser's file selector, isn't possible.
To do that you have to use a mixed type of upload, such as SWFUpload, based on a flash uploader system (that's a really nice techinque: it allows you to post more than a file at time).
The only thing you can do in standard mode is to filter the already posted file, and I suggest to use System.IO.Path namespace utility:
if (Path.GetExtension(upFile.FileName).ToUpper().CompareTo(".DOT") == 0)
{
/* do what you want with file here */
}
Check the filename of the uploaded file serverside:
FileUpload1.PostedFile.FileName
Unless you want to use java or something similar on the client, there's really not much you can do for filtering uploaded files before they're sent to the server.
Here I have a small method that I used to filter which types of files can be uploaded by the fileupload control named fuLogo.
if (fuLogo.HasFile)
{
int counter = 0;
string[] fileBreak = fuLogo.FileName.Split(new char[] { '.' });
logo = Server.MapPath("../Images/Logos/" + fileBreak[0] + counter.ToString()+ "." + fileBreak[1]);
if (fileBreak[1].ToUpper() == "GIF" || fileBreak[1].ToUpper() == "PNG")
{
while (System.IO.File.Exists(logo))
{
counter++;
logo = Server.MapPath("../Images/Logos/" + fileBreak[0] + counter.ToString() + "." + fileBreak[1]);
}
}
else
{
cvValidation.ErrorMessage = "This site does not support any other image format than .Png or .Gif . Please save your image in one of these file formats then try again.";
cvValidation.IsValid = false;
}
fuLogo.SaveAs(logo);
}
basically, I first Iterates through the directory to see if a file already exists. Should the file exist, (example picture0.gif) , it will increase the counter (to picture1.gif). It prevents that different users will overwrite each other's pictures should their pictures have the same name.