Shihan Khan
Shihan Khan

Reputation: 2188

Change image format using WebImage

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.

Upvotes: 0

Views: 2217

Answers (2)

Sum None
Sum None

Reputation: 2279

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

Upvotes: 1

Cognis
Cognis

Reputation: 65

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

Upvotes: 1

Related Questions