Asked by:
how to convert base64 to image and save to database in asp.net c#?

Question
-
User-1647172364 posted
Hlo Professionals!
I want to convert base 64 to image and save to data base in asp.net c#
Thursday, July 9, 2020 6:54 AM
All replies
-
User288213138 posted
Hi sanam13,
I want to convert base 64 to image and save to data base in asp.net c#I made demo for you as a refernce, first I get the base64String by converting the image, then convert this base64String to a image, and finally save the image to the database through the FileUpload1 control.
<asp:Button ID="Button1" runat="server" OnClick="ImageToBase_Click" Text="Image to Base64" /> <asp:TextBox ID="TextBox1" runat="server" Height="146px" TextMode="MultiLine"></asp:TextBox> <br /> <asp:Button ID="Button2" runat="server" OnClick="BaseToImage_Click" Text="Base64 To Image" /> <asp:Image ID="Image1" runat="server" Height="157px" Width="168px" /> <br /> <asp:FileUpload ID="FileUpload1" runat="server" /> <asp:Button ID="Button3" runat="server" OnClick="Button3_Click" Text="Save to database" /> static string base64String = null; public string ImageToBase64() { string path = @"C:\Users\Samwu.WICRESOFT\Desktop\image\1.PNG"; using (System.Drawing.Image image = System.Drawing.Image.FromFile(path)) { using (MemoryStream m = new MemoryStream()) { image.Save(m, image.RawFormat); byte[] imageBytes = m.ToArray(); base64String = Convert.ToBase64String(imageBytes); return base64String; } } } public System.Drawing.Image Base64ToImage() { byte[] imageBytes = Convert.FromBase64String(base64String); MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length); ms.Write(imageBytes, 0, imageBytes.Length); System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true); return image; } protected void ImageToBase_Click(object sender, EventArgs e) { TextBox1.Text = ImageToBase64(); } protected void BaseToImage_Click(object sender, EventArgs e) { Base64ToImage().Save(Server.MapPath("~/Images/Hello.jpg")); Image1.ImageUrl = "~/Images/Hello.jpg"; } protected void Button3_Click(object sender, EventArgs e) { foreach (HttpPostedFile postedFile in FileUpload1.PostedFiles) { string filename = Path.GetFileName(postedFile.FileName); string contentType = postedFile.ContentType; using (Stream fs = postedFile.InputStream) { using (BinaryReader br = new BinaryReader(fs)) { byte[] bytes = br.ReadBytes((Int32)fs.Length); string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { string query = "insert into Test7 values (@Name, @ContentType, @Data)"; using (SqlCommand cmd = new SqlCommand(query)) { cmd.Connection = con; cmd.Parameters.AddWithValue("@Name", filename); cmd.Parameters.AddWithValue("@ContentType", contentType); cmd.Parameters.AddWithValue("@Data", bytes); con.Open(); cmd.ExecuteNonQuery(); con.Close(); } } } } } }
My table structure:
Best regards,
Sam
Thursday, July 9, 2020 8:20 AM -
User348806598 posted
May not be a good idea to store images in the database, this will increase database size. You can rethink the design. One approach you can follow is to save the file in a physical drive and add the reference file to the database. You can also store files in the cloud.
Thursday, July 9, 2020 9:05 AM -
User-1647172364 posted
OK Sir your code is working but the way you are using its static because u already providing image path in your c# code. I have made some changes in your code and applied in my code perhaps it is working but base64 to image is not working.
Here is my code
Please execute it.,
Aspx <asp:TextBox ID="TextBox1" runat="server" Height="146px" TextMode="MultiLine"></asp:TextBox> <asp:Button ID="btnUpload" runat="server" Text="Upload" onclick="btnUpload_Click" BackColor="#3366CC" BorderColor="#3366CC" ForeColor="White" /> <asp:Image ID="Image1" runat="server" Height="157px" Width="168px" /> C# using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.IO; using System.Drawing; using System.Web.UI.WebControls; namespace WebApplication14 { public partial class WebForm41 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { } } protected void btnUpload_Click(object sender, EventArgs e) { //***Convert Image File to Base64 Encoded string***// //Read the uploaded file using BinaryReader and convert it to Byte Array. BinaryReader br = new BinaryReader(FileUpload1.PostedFile.InputStream); byte[] bytes = br.ReadBytes((int)FileUpload1.PostedFile.InputStream.Length); //Convert the Byte Array to Base64 Encoded string. string base64String = Convert.ToBase64String(bytes, 0, bytes.Length); TextBox1.Text = base64String; int status = 0; using (SchoolEntities2 ctx = new SchoolEntities2()) { ctx.packages.Add(new package() { bytess = base64String.ToString(), by_whom = Session["username"].ToString(), date_time = System.DateTime.Now.ToLocalTime(), }); status = ctx.SaveChanges(); } byte[] imageBytes = Convert.FromBase64String(base64String); //string filePath = Server.MapPath(base64String); Image1.ImageUrl = base64String + imageBytes; //File.WriteAllBytes(filePath, imageBytes); //***Save Base64 Encoded string as Image File***// //Convert Base64 Encoded string to Byte Array. //byte[] imageBytes = Convert.FromBase64String(base64String); } } }
Friday, July 10, 2020 5:50 AM -
User288213138 posted
Hi sanam13,
I have made some changes in your code and applied in my code perhaps it is working but base64 to image is not working.Image1.ImageUrl = base64String + imageBytes;
Your question is the image is not displayed when converting base64String to image?
The Image.ImageUrl Property gets or sets the URL that provides the path to an image to display in the Image control. but yours is base64String and imageBytes.
So you need to convert base64String to a image to display.
TextBox1.Text = base64String; byte[] imageBytes = Convert.FromBase64String(base64String); MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length); ms.Write(imageBytes, 0, imageBytes.Length); System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true); image.Save(Server.MapPath("the image path")); Image1.ImageUrl = "the image path";
Best regards,
Sam
Friday, July 10, 2020 7:42 AM -
User-1647172364 posted
Sir I have applied Your code i am getting error on this code System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true); and the error is :-
System.ArgumentException: 'Parameter is not valid
Friday, July 10, 2020 8:25 AM -
User288213138 posted
Hi sanam13,
System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);System.ArgumentException: 'Parameter is not validIt works fine on my side, please check if your ms is correct.
Best regards,
Sam
Friday, July 10, 2020 9:34 AM -
User-1647172364 posted
Ok that all right but your code is also static sir because you are also giving image path there in your code.
image.Save(Server.MapPath("the image path")); Image1.ImageUrl = "the image path";
See sir When i upload image from file upload that is converted to base 64 in given textbox
and my requirement is that base 64 code should be converted it into Image in image (and image should be any of it) control on that web page.Friday, July 10, 2020 10:21 AM -
User288213138 posted
Hi sanam13,
sanam13
my requirement is that base 64 code should be converted it into Image in image (and image should be any of it) control on that web pageYou only need to add a different file name to it when saving the file.
BinaryReader br = new BinaryReader(FileUpload1.PostedFile.InputStream); byte[] bytes = br.ReadBytes((int)FileUpload1.PostedFile.InputStream.Length); //Convert the Byte Array to Base64 Encoded string. string base64String = Convert.ToBase64String(bytes, 0, bytes.Length); TextBox1.Text = base64String; byte[] imageBytes = Convert.FromBase64String(base64String); MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length); ms.Write(imageBytes, 0, imageBytes.Length); System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true); image.Save(Server.MapPath("~/Images/"+ Path.GetFileName(FileUpload1.PostedFile.FileName))); Image1.ImageUrl = "~/Images/"+ Path.GetFileName(FileUpload1.PostedFile.FileName);
Best regards,
Sam
Monday, July 13, 2020 8:23 AM