converting an image to png on upload
Asked Answered
A

3

8

When a user uploads a jpg/gif/bmp image, I want this image to be converted to a png image and then converted to a base64 string.

I've been trying to get this to work but I've hit a brick wall really, can anyone help me out please?

My current code without the image conversion is below:

public ActionResult UploadToBase64String(HttpPostedFileBase file)
        {

                var binaryData = new Byte[file.InputStream.Length];
                file.InputStream.Read(binaryData, 0, (int) file.InputStream.Length);
                file.InputStream.Seek(0, SeekOrigin.Begin);
                file.InputStream.Close();

                string base64String = Convert.ToBase64String(binaryData, 0, binaryData.Length);

...
}
Alkane answered 25/6, 2013 at 10:18 Comment(1)
Take a look at #254919Instrumentation
W
31

You're not converting it at all there.. you can use something like this:

using System.Drawing;

Bitmap b = (Bitmap)Bitmap.FromStream(file.InputStream);

using (MemoryStream ms = new MemoryStream()) {
    b.Save(ms, ImageFormat.Png);

    // use the memory stream to base64 encode..
}
Woolcott answered 25/6, 2013 at 10:23 Comment(1)
+1 for doing it in memory. Obviously you want to work with the image if your converting it for some reason. The other answers all want to write it to disk immediately.Centrosome
I
2

You can convert to PNG in temp folder and then upload it.

private string GetConvertedPNGFile(string imagename)
{
    var bitmap = Bitmap.FromFile(imagename);
    b.Save(Path.GetFileName(imagename) + ".png", ImageFormat.Png);
    return Path.GetFileName(imagename) + ".png";
}

Now upload the changed file and then delete the converted file.

Intransitive answered 25/6, 2013 at 10:27 Comment(3)
Then it'll be deleted after upload.Intransitive
..you can do it entirely in-memory though.. without the extra steps of writing to disk and deleting it afterwards..Woolcott
Sure but this is also a way for that.Intransitive
B
0

This code is use for save image in png format in a folder in asp.net

#region Save image in Png format
string imgName1 = "Photo_" + lblCode.InnerText;

            Guid uid1 = Guid.NewGuid();
            string PhotoPath1 = Server.MapPath("~/Employee/EmpPngPhoto/") + lblCode.InnerText;
            string SavePath1 = PhotoPath1 + "\\" + imgName + ".png";
            if (!(Directory.Exists(PhotoPath1)))
            {
                Directory.CreateDirectory(PhotoPath1);
            }
            System.Drawing.Bitmap bmpImage1 = new System.Drawing.Bitmap(fuPhotoUpload.PostedFile.InputStream);
            System.Drawing.Image objImage1 = ScaleImage(bmpImage1, 160);
            objImage.Save(SavePath1, ImageFormat.Png);
            #endregion
Brookner answered 3/8, 2018 at 6:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.