Saving A Base64 String As An PNG Image Into A Folder

In This Article, I Will Show You How A Base64 String Can Be Converted Into The JPG Or PNG Image And Save In Local Folder.

Now Let’s Start

  • Create an Empty Web API
  • Create an Image API controller.
  • Create A Folder Where We Want To Save The Images.

Now Put The Bellow Code Into The Image Controller.

I Want To Check The Image Type Before Saving The Image In Folder. So I’ve Written The Following Extension to Check The Type Of A Base64 String. And You Can Show That I make A Function For Extension And Give  The Switch Statement For Save The Image Into Folder According To Image Type.

Here Is My Code:

using System;
using System.IO;
using InvoiceWebApi.Authentication;
using InvoiceWebApi.Model;
using Microsoft.AspNetCore.Mvc;

namespace ImageWebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ImageController : ControllerBase
    {

        private readonly ApplicationDbContext _context;

        public ImageController(ApplicationDbContext context)
        {
            _context = context;
        }

        [HttpPost]
        public ActionResult<object> postImg([FromBody]  Image Image)
        {
            try
            {
                String path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\Images\\");

                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);
                var data = Image.base64Image.Substring(0, 5);
                var extension = Extension(data);
                var imageName = string.Format(@"{0}", Guid.NewGuid()) + extension;

                string imgPath = Path.Combine(path, imageName);
                var imageBytes = Convert.FromBase64String(Image.base64Image);
                var imagefile = new FileStream(imgPath, FileMode.Create);
                imagefile.Write(imageBytes, 0, imageBytes.Length);
                imagefile.Flush();

                Image image = new Image
                {
                    base64Image = imageName
                };

                if (ModelState.IsValid)
                {
                    _context.images.Add(image);
                    _context.SaveChanges();

                }
                return Ok(image);
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }
        public string Extension(string image)
        {
            var extension = "";
            switch (image.ToUpper())
            {
                case "IVBOR":
                    return extension = ".png";
                case "/9J/4":
                    return extension = ".jpg";

            }
            return extension;
        }

    }
}

Now Let’s Check  Above Code Is Working Or Not. Open Postman And Run the API.

Let’s Check Server Folder, You Will Able To See Your Image.

Submit a Comment

Your email address will not be published. Required fields are marked *

Footer Logo

Subscribe

Select Categories