Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a new image on the file system from System.Drawing.Image?

Ok, I'm sorry, this is probably a noob question but I'm kinda stuck.

So what I'm doing (on my asp.net application) is loading an image from the file system:

System.Drawing.Image tempImage;
tempImage = System.Drawing.Image.FromFile(HttpContext.Server.MapPath(originalPath));

Then I do some resizing:

tempImage = my awesomeResizingFunction(tempImage, newSize);

and intend to save it to the file system in another location using this:

string newPath = "/myAwesomePath/newImageName.jpg";
tempImage.Save(newPath);

and what I get is this error:

"A generic error occurred in GDI+."

I know the image is "ok" because I can write it out to the browser and see the resized image, I only get the error when I try to save it. I'm kinda new and stuck, am I doing this totally wrong? (Well, i guess that's obvious but you know what I mean...)

like image 535
Paul Mignard Avatar asked Dec 13 '22 03:12

Paul Mignard


1 Answers

Try this code... I have used the same code for resizing image and saving.

    System.Drawing.Bitmap bmpOut = new System.Drawing.Bitmap(NewWidth, NewHeight);
    System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmpOut);
    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
    g.FillRectangle(System.Drawing.Brushes.White, 0, 0, NewWidth, NewHeight);
    g.DrawImage(new System.Drawing.Bitmap(fupProduct.PostedFile.InputStream), 0, 0, NewWidth, NewHeight);
    MemoryStream stream = new MemoryStream();
    switch (fupProduct.FileName.Substring(fupProduct.FileName.IndexOf('.') + 1).ToLower())
    {
        case "jpg":
            bmpOut.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
            break;
        case "jpeg":
            bmpOut.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
            break;
        case "tiff":
            bmpOut.Save(stream, System.Drawing.Imaging.ImageFormat.Tiff);
            break;
        case "png":
            bmpOut.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
            break;
        case "gif":
            bmpOut.Save(stream, System.Drawing.Imaging.ImageFormat.Gif);
            break;
    }
    String saveImagePath = Server.MapPath("../") + "Images/Thumbnail/" + fupProduct.FileName.Substring(fupProduct.FileName.IndexOf('.'));
    bmpOut.Save(saveImagePath);

where fupProduct is fileupload control ID

like image 180
Muhammad Akhtar Avatar answered Mar 01 '23 17:03

Muhammad Akhtar